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

Choose or deselect images from a selection

I am currently working on a feature for an album creation tool where users can select photos from a pool of images and assign them to a specific folder. However, I'm facing difficulty in selecting individual photos and applying customized attributes t ...

The Vue Router Replace function continues to activate the created() lifecycle hook

I am working on a view page that contains multiple tabs. Whenever the index of a tab changes, I make an update. For example, when you click on the "Info" tab: this.$router.replace({query: { section: 'Info'} }) What I want to achieve is - myUrl/ ...

Strategies for aligning a div element in the middle of the screen

Positioned in the center of the current viewport, above all other elements. Compatible across different browsers without relying on third-party plugins, etc. Can be achieved using CSS or JavaScript UPDATE: I attempted to use Javascript's Sys.UI.Dom ...

What is the connection between serialization and JSON?

Can you explain serialization? Serialization is the process of converting an object into a stream of bytes, allowing it to be sent over a network or stored in a file. This allows the object to be reconstructed later on. What exactly is JSON? JSON stands ...

switchMap: Triggering multiple requests simultaneously (2)

Currently, I am utilizing Angular 2 RC-4 and facing an issue where a network request is being triggered twice whenever there is a change in the input box. This is what my code looks like: component.ts this.term = new Control(); this.suggestions = this. ...

The Vue component table is not showing any retrieved data

Seeking help as a newcomer to the world of Laravel and Vue.js. Trying to populate data on a Vue component, but facing an issue with the tableData variable in the axios.get response. It is not rendering the array data onto the table as expected. Could there ...

The Google map is not showing up on the screen despite having entered the API Key

Trying to showcase a Google map on my website. Check out the code below:- <script> function initializeMap() { var coords = {lat: -25.363, lng: 131.044}; var mapObj = new google.maps.Map(document.getElementById('mapz') ...

Discovering the method for accessing a variable within jQuery from a regular JavaScript function

As someone new to jQuery, I am currently facing a challenge with accessing a variable defined inside a jQuery block from a regular function. Despite my attempts, I have been unsuccessful in accessing it. Can anyone guide me on how to do this? <script l ...

Tips on building a carousel with slot elements

Many people have shown me the traditional way of creating a carousel using an array of images. However, I find this method to be limiting because I want each slide of my carousel to include a lightbox component. Instead of having to rewrite the lightbox fu ...

Experiencing difficulty with loading elements into their respective containers

My goal is to limit the number of alert elements loaded in each .content container to a maximum of 9, but currently I am grouping every 10 items together and discarding any remaining items! For instance, if a random value is 8, then no content will be dis ...

Replace a single Vuetify icon with a Font Awesome SVG icon

Can individual icons from Vuetify be replaced with Font Awesome svg icons directly, without the need for a custom component for each icon? For example: import { svgPathData as envelopeSvg } from '@fortawesome/free-solid-svg-icons/faEnvelope' imp ...

Every time I click once, two unnecessary AJAX calls are triggered, and the DOM remains outdated until I manually refresh the page

Whenever I click on a span, it sends an ajax request to delete the clicked todo from the database. However, in the DOM, the item is not removed until I refresh the page. Here is my index.html file: <ul class="list"> </ul> I noticed ...

Attempting to develop a next.js web application using Vercel has hit a roadblock for me. Upon running the "vercel dev" command in the terminal, an error message is

vercel dev Vercel CLI 28.5.3 > Creating initial build node:events:491 throw er; // Unhandled 'error' event ^ Error: spawn cmd.exe ENOENT at ChildProcess._handle.onexit (node:internal/child_process:285:19) at onErrorNT (nod ...

Remove all HTML tags except for those containing a specific class

Looking for a regex that removes all HTML tags except the "a" tags with the "classmark" class For example, given this HTML string: <b>this</b> <a href="#">not match</a> <a href="#" target="_blank" ...

What is the most common method for creating a dropdown menu for a website's navigation?

Is there a common approach to creating an interactive drop-down navigation menu in the industry? I have searched on Google and found multiple methods, but as a student working on my first big web project, I am hoping to find a standard practice. I don&apo ...

What is the best way to specify option values for selection in AngularJS?

...while still maintaining the model bindings? I currently have a select menu set up like this: <select class="form-control" ng-model="activeTask" ng-options="task.title for task in tasks"> </select> When an option is selected, it displays s ...

Exploring the mocking of document,hidden using Jasmine

Struggling to simulate document.hidden in an angular unit test, but facing issues. Tried the following solutions: spyOn(Document.prototype, <any>'hidden').and.returnValue(true); spyOn(Document, <any>'hidden').and.ret ...

Error in AngularJS v1.2.5 when using textarea with placeholder attribute in IE11

Having trouble with an Angular JS v1.2.5 form that is not functioning in IE11, despite working perfectly in Firefox, Chrome, and Safari. The issue seems to be related to using interpolation inside the placeholder attribute of a textarea. <body ng-con ...

Utilize the <a> element as a button to submit the data form

I am looking to transfer data from a form to another PHP page without using a button within the form itself. Instead, I have placed a separate button outside of the form for submission. How can I achieve this by sending the form data to the other page? Bel ...

Incorporate classes into span elements with Vue 3 on click event

In order to add a class to the element when clicked, you can use the span element as a checkbox. However, there seems to be an issue with selecting multiple elements at once <div v-for="(item, index) in listTimes"> <span class="ch ...