Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use the computed properties to compute another properties in Vue?

If I have a two computed properties like this,

computed: {
  id: function(){ return this.$route.query.id; },
  hasId: function(){ return this.$route.query.id !== undefined; }
}

how can I use id to compute hasId like this pseudo-code?

computed: {
  id: function(){ return this.$route.query.id; },
  hasId: function(){ return id !== undefined; }
}
like image 631
Konrad Viltersten Avatar asked Dec 15 '16 21:12

Konrad Viltersten


People also ask

Can I use computed property in data Vue?

In Vue. js, computed properties enable you to create a property that can be used to modify, manipulate, and display data within your components in a readable and efficient manner. You can use computed properties to calculate and display values based on a value or set of values in the data model.

Can I pass parameter to computed Vue?

Conclusion: The computed property is a very powerful feature of Vue. js, and we have learned that it comes in handy when we have to change them when their dependencies get changed. We have learned to pass the parameter and use it in the computed property.

Can we pass parameters to computed property?

No, you can't pass parameters to computed properties.

What is the difference between a computed property and methods in VUE JS?

Instead of a computed property, we can define the same function as a method. For the end result, the two approaches are indeed exactly the same. However, the difference is that computed properties are cached based on their reactive dependencies.


2 Answers

You need to use correct scope to access a vue computed property.

as you are using just id, it will search it in global scope and not find it and will return undefined. For getting vue computed property, you need to do: this.id, so your code will look like following:

computed: {   id: function () { return this.$route.query.id; },   hasId: function () { return this.id !== undefined; } } 

Inside a component, this refers to our Vue instance. However you can access $route and other similar function from this, as they are defined at Vue.prototype, see below code from vue-router:

 Object.defineProperty(Vue.prototype, '$route', {     get: function get$1 () { return this.$root._route }  }) 
like image 144
Saurabh Avatar answered Oct 03 '22 01:10

Saurabh


your pseudo code was very close. Just change id to this.id

computed: {   id: function(){ return this.$route.query.id; },   hasId: function(){ return this.id !== undefined; } } 
like image 41
aaaaaa Avatar answered Oct 03 '22 02:10

aaaaaa