Access vue instance/data inside filter method

2019-01-28 10:58发布

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

4条回答
Juvenile、少年°
2楼-- · 2019-01-28 11:45

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>

查看更多
萌系小妹纸
3楼-- · 2019-01-28 11:46

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:

filters are primarily designed for text transformation purposes. For more complex data transforms in other directives, you should use Computed properties instead.

查看更多
贼婆χ
4楼-- · 2019-01-28 11:49

Like this:

new Vue({
 data:{
  amount: 10,
  exchangeRate:60
 },
 el:"#app",
 filters:{
   currency: function(amount, exchange){
             console.log(exchange);
             //return amount * this.exchangeRate; <- can't do, must pass it in
            return amount * exchange;

   }
 }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
 {{ amount | currency(exchangeRate)}}
</div>

查看更多
孤傲高冷的网名
5楼-- · 2019-01-28 12:00

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.

Use computed properties for local, component-specific data transforms. Similar to filters, computed getters should be pure.

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.

(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.

查看更多
登录 后发表回答