Dynamic way to fetch computed properties in VueJS

I am trying to find a way to calculate the sum of computed properties that begin with the string calculateSum.

The challenge is that I cannot access their names using this.computed.

Here is my approach:

getSubTotal(){
    var computed_names = [];
    var computed_names_filtered = computed_names.filter(x => {return x.startsWith('calculateSum')})
    return _.sum(computed_names_filtered.map(x => eval(x+'()'))
}

Can you think of another way to achieve this task?

Answer №1

Here is a quick snippet that may assist you in accessing the computed properties list:

this.$options.computed

Answer №2

You have the ability to dynamically access them using this['computed_name'] with the use of the bracket accessor since the component instance acts as an object :

var computed_names = Object.keys(this);
var computed_names_filtered = 
computed_names.filter(x => {return x.startsWith('calculateSum')})
 _.sum(computed_names_filtered.map(x => this[x]))

Please note that when calling the computed property, you should not include (), however if you intend to invoke a method you can use this['method_name']()

Here is an example:

// ignore these two lines below, they are for disabling warnings in "Run code snippet"
Vue.config.devtools = false;
Vue.config.productionTip = false;

new Vue({
  el: '#app',
  computed: {
    op1() {
      return 1;
    },
    op2() {
      return 2;
    },
    op3() {
      return 23;
    },
    total() {
      return ['op1', 'op2', 'op3'].map(o => this[o]).reduce((acc, curr) => acc += curr, 0)

    }
  },
   
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>


<div id="app" class="container">
  {{total}}
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Vue to change select box data separately

I have a functional select box that is currently sending the selected value to a method when the change event occurs. However, I am wondering about something: Let's say I also want to send the cat_id value at the time of selection (to create an objec ...

Check the box to show the corresponding sections of the form

.If there are two checkboxes with options true or false, how should I handle a third checkbox? I want to display different parts of the form based on the selection of the checkboxes. ...

What is the best way to incorporate a custom string into an Angular application URL without disrupting its regular operation?

In my Angular application with angular ui-router, I am facing an issue with the URL structure. When I access the application from the server, the URL looks like localhost/..../index.html. Once I click on a state, the URL changes to localhost/.../index.htm ...

Why is there a discrepancy between the value displayed in a console.log on keydown and the value assigned to an object?

As I type into a text box and log the keydown event in Chrome, I notice that it has various properties (specifically, I'm interested in accessing KeyboardEvent.code). Console Log Output { altKey: false bubbles: true cancelBubble: false cancelable: t ...

A guide on sending arrays from javascript to a Laravel controller through axios

Currently, I am utilizing Laravel 5.4 and Vue 2 to manage my data. I am facing an issue where I need to call a controller method using axios while passing two arrays. These arrays are crucial for making database requests in the controller and retrieving ne ...

What is the best way to extract information from a JSON XHR request and incorporate it into my template?

I am brand new to using Ember. Right now, my main goal is to connect to an API that provides random text and then show that text on a webpage. The specific API endpoint I am using is "" which will give back a response in JSON format. app/controllers/rando ...

What is the best way to execute a JavaScript function when the onSelect event of a jQuery datepicker is

Is there anyone who can assist me? I am currently working with a JavaScript function: function updateAb(param){ some manipulation } I also have a datepicker jQuery plugin that I am using for the onSelect event, like so: $( ".datepicker").datepicker({onS ...

Converting MongoDB Queries to MySQL in Node: A Step-by-Step Guide

I am currently facing a challenge where I need to migrate my app's database from mongoDB to mysql. The application was initially developed using node.js, but I encountered an issue with the "Create table" query while attempting the conversion process. ...

Failure in Retrieving Fresh Information via Ajax Call

My web application utilizes polling to constantly update the status of a music player. To achieve this, I have implemented a method using setInterval to execute an Ajax call every half second. This setup functions as intended on a variety of browsers inclu ...

How do I prevent my image slider from scrolling to the top of the page when I click next or prev?

<script> export default { name: "ImageSlider", data() { return { images: [ "https://cdn.pixabay.com/photo/2015/12/12/15/24/amsterdam-1089646_1280.jpg", "https://cdn.pixabay.com/photo/2016/02/17/2 ...

Tips for showcasing several images with accompanying content once the webpage has finished loading

I am faced with an issue on my PHP website. The website is a social networking platform with numerous images and contents. I am seeking a way to first display only the content to the user, then show the images after they have all finished loading. Addition ...

Removing duplicate values in Vue after sorting

Explore <div v-for="todo in sortedArray"> <b-button block pill variant="outline-info" id="fetchButtonGap" v-model:value="todo.items[0].arrivalTime"> {{fromMilTime(todo.items[0].arrivalTime)}} < ...

The dilemma between installing Electron or installing Electron-Builder: which one

When it comes to installing Electron for an Electron app with React, the method can vary depending on the tutorial. Some tutorials use electron-builder while others do not, but there is little explanation as to why. First: npx create-react-app app cd app ...

What is the best way to display elements in a v-for loop with varying intervals?

Is there a way to use the v-for loop to display elements of an array at specific time intervals? For instance, could I show the first element after 100ms, the second after 200ms, and so on for subsequent elements? If so, what would be the solution to ach ...

Bypass domain restrictions on JavaScript in Firefox version 7.0

As I work on a personal HTML + JS app, the ability to access the content of iframes or opened windows with Javascript would be extremely beneficial in boosting my productivity. I am curious if there is a way to bypass the cross domain restrictions set by ...

Invoke a method on a child component once an event has been emitted

Currently, I am working on creating a custom button component that includes a spinner. The functionality works well - the button gets disabled and displays a spinner upon click. However, I am facing issues when it comes to resetting the button's state ...

*NgFor toggle visibility of specific item

Here is a snippet of HTML code that I'm working with: <!-- Toggle show hide --> <ng-container *ngFor="let plateValue of plateValues; let i=index"> <button (click)="toggle(plateValue)">{{i}}. {{ btnText }}</button> ...

changing the css transformation into zoom and positioning

My goal is to incorporate pinch zoom and panning using hardware-accelerated CSS properties like transform: translate3d() scale3d(). After completing the gesture, I reset the transform and switch to CSS zoom along with absolute positioning. This method ensu ...

Steps for implementing a select all feature with jQuery

I'm currently working on a jQuery function that is acting as a select-all option. Everything is functioning correctly except that when I deselect any of the child elements from select all, the option remains enabled. My goal is to enable or disable th ...

Create a JavaScript function that accepts an argument and can be called both with and

Does anyone know how this code works? function animate(t) { sun.rotation.y = t/1000; renderer.clear(); camera.lookAt(sun.position); renderer.render(scene, camera); window.requestAnimationFrame(animate, renderer.domElement); ...