如何在 Vuejs 组件中应用过滤器
How to apply a filter within a Vuejs component?
如果我有一个简单的过滤器,请说:
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 问题。
要使用 getter 和 setter,计算属性是完美的:
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>
您可以为每个组件添加本地筛选器:
filters: {
filterName: function (value) {
// some logic
var result = ....
//
return result;
}
}
调用该筛选器:
<div> {{ value | filterName }} </div>
筛选器只能具有组件的作用域(与指令或转换相同)。 您需要注册它组件级别。你在 VueJS 文档中有一个很好的例子
var Child = Vue.extend({ /* ... */ })
var Parent = Vue.extend({
template: '...',
components: {
// <my-component> will only be available in Parent's template
'my-component': Child
}
})
希望这有帮助。有关信息可在以下位置找到: http://vuejs.org/guide/components.html#Local_Registration
相关文章:
- 角度ng重复显示应用过滤器之前的数据
- Vue js 在输入字段中对 v-model 应用过滤器
- JQGridPageing在通过过滤器工具栏应用过滤器后非常慢
- 如何在嵌套的ngRepeat中对第二个ngRepeat应用过滤器
- 在应用过滤器之前,我需要隐藏所有过滤器容器数据
- DC.js 应用过滤器后热图颜色范围未更新
- 应用过滤器后元素被删除
- free-jqgrid:保存、加载和应用过滤器数据的更简单方法,包括过滤器工具栏文本和页面设置
- 在 ExtJS 4.1 的 Ext.Data.TreeStore 中应用过滤器
- 如何在 Vuejs 组件中应用过滤器
- AngularUI:在应用过滤器的情况下正确更新两个列表之间的模型
- Angular.js-使用间隔应用过滤器
- jQuery点击按钮don'在剑道网格中应用过滤器后无法工作
- jQuery在应用过滤器后调整窗口大小
- 使用jQuery对选择框应用过滤器
- 当应用过滤器时,DC.js复合图表不更新
- 如何使用ng-repeat为2维json对象应用过滤器
- AngularJS在控制器中应用过滤器
- 是否有可能在特定维度上应用过滤器
- 从不同的控制器应用过滤器到ngRepeat