在过滤器方法中访问 vue 实例/数据 [英] Access vue instance/data inside filter method

查看:44
本文介绍了在过滤器方法中访问 vue 实例/数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试像这样访问过滤器函数中的 vue 实例数据.JS:-

new Vue({数据:{数量:10,汇率:50},el:"#app",过滤器:{货币:功能(金额){控制台日志(这个);//返回金额* this.exchangeRate;退货金额*50;}}})

HTML:

{{ 金额 |货币}}

我的目标是使用 return amount * this.exchangeRate; 但是 this 在这里等于 window .我怎样才能做到这一点 ?谢谢.jsfiddle

解决方案

据 Vue 的创造者 Evan 所说:

<块引用>

主要使用方法来触发状态更改.当你调用一个方法时,它通常意味着一些副作用.

过滤器主要用于需要在整个应用中重复使用的简单文本格式.过滤器应该是纯粹的 - 没有副作用,只有数据输入和数据输出.

将计算属性用于本地、特定于组件的数据转换.与过滤器类似,计算得到的 getter 应该是纯的.

有一种特殊情况,您想使用仅在模板中可用的范围变量(例如 v-for 别名)来计算某些内容,在这种情况下,可以使用辅助方法";这样你就可以通过传递参数来计算某些东西.

(来源:https://forum-archive.vuejs.org/topic/830/method-vs-computed-vs-filter/2)

因此,由于过滤器取决于组件,我认为在这种情况下您应该使用计算属性而不是过滤器.

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

解决方案

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.

这篇关于在过滤器方法中访问 vue 实例/数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆