I'm trying to access vue instance data inside filter function like this. JS:-
new Vue({
data:{
amount: 10,
exchangeRate:50
},
el:"#app",
filters:{
currency: function(amount){
console.log(this);
//return amount * this.exchangeRate;
return amount *50;
}
}
})
HTML:
<div id="app">
{{ amount | currency}}
</div>
My goal is to use return amount * this.exchangeRate;
but this
is equal to window
here.
How can I do this ?
Thanks.
jsfiddle
I had this problem, and a quick and easy way I found was to do this above the function:
let self = this
Then I could just call
self.<name of data property or function>
I see there are two options you have, either use a method/computed property or pass additional parameter to filter. You can not access
this
inside filter, as purpose of filter is simple like text transformation, etc. from the docs:Like this:
According to Evan, the creator of Vue:
(source: https://forum-archive.vuejs.org/topic/830/method-vs-computed-vs-filter/2)
So, since the filter depends on the component, I think you should use a computed property in this case instead of a filter.