如果我有一个简单的过滤器,请说:
Vue.filter('foo', function (value) {
return value.replace(/foo/g, 'bar');
});
还有一个简单的组件:
Vue.component('example', {
props: {
msg: String,
},
});
在标记内:
<example inline-template :msg="My foo is full of foo drinks!">
{{ msg }}
</example>
我可以简单地应用过滤器:
<example inline-template :msg="My foo is full of foo drinks!">
{{ msg | foo }}
</example>
我可以轻松地在模板中应用过滤器,但我想将该逻辑移回到组件中。
它不需要成为过滤器,但基本上是一种为数据字段创建 getter 和 setter 的方法。
类似于:
Vue.component('example', {
props: {
msg: {
type: String,
getValue: function(value) {
return value.replace(/foo/g, 'bar');
},
}
},
});
最佳答案
它有点隐藏,我不确定它是否被记录在案,但有一个 Github issue on how to use filters in components .
要使用 getter 和 setter,computed properties是完美的:
Vue.component('example', {
props: {
msg: {
type: String,
}
},
computed: {
useMsg: {
get: function() {
return this.$options.filters.foo(this.msg);
},
set: function(val) {
// Do something with the val here...
this.msg = val;
},
},
}
});
以及相应的标记:
<example inline-template :msg="My foo is full of foo drinks!">
{{ useMsg }}
</example>
关于javascript - 如何在 Vuejs 组件中应用过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266157/