访问过滤器方法中的vue实例/数据 [英] Access vue instance/data inside filter method
问题描述
我正在尝试像这样访问过滤器函数中的vue实例数据。
JS: -
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>
我的目标是使用返回金额* this.exchangeRate;
但此
等于窗口
此处。
我该怎么办?
谢谢。
jsfiddle
My goal is to use return amount * this.exchangeRate;
but this
is equal to window
here.
How can I do this ?
Thanks.
jsfiddle
推荐答案
根据Vue的创建者Evan的说法:
According to Evan, the creator of Vue:
主要使用方法来触发状态变更。当你调用一个方法时,它通常意味着一些副作用。
Use methods primarily for triggering state alterations. When you call a method, it generally implies some side effect.
使用过滤器主要用于需要在整个应用程序中重复使用的简单文本格式。过滤器应该是纯粹的 - 没有副作用,只有数据和数据输出。
Use filters primarily for simple text formatting that needs to be reused all across your app. Filters should be pure - no side effects, just data in and data out.
使用计算属性进行本地,特定于组件的数据转换。与过滤器类似,计算出的getter应该是纯粹的。
Use computed properties for local, component-specific data transforms. Similar to filters, computed getters should be pure.
有一种特殊情况,你想使用只在模板中可用的范围变量来计算某些东西(例如a v-for alias),在这种情况下,可以使用辅助方法,这样你就可以通过传递参数来计算某些东西。
There is a special case where you want to compute something using a scope variable that is only available in the template (e.g. a v-for alias), in such cases it's okay to use "helper methods" so that you can compute something by passing it arguments.
(来源: 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.
这篇关于访问过滤器方法中的vue实例/数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!