组件中的Vue过滤器

时间:2018-03-15 11:16:03

标签: filter vue.js vuejs2 vue-component

[Vue warn]: Property or method "onlyNumbers" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

<template>
<div class="category-info">
    <div v-for="input in inputs.text">
        <label >{{ input.placeholder}}</label>
        <input type="text"  id="location" :name="input.name" v-model="input.value | onlyNumbers" @change="inputChange">
    </div>
    <div class="select" v-for="select in inputs.select">
        <label >{{ select.placeholder }}</label>
        <my-select :data="select" v-model="select.value" @change="selectChange(select)"></my-select>
    </div>
</div>

大家好我想从输入文本中过滤值,我用2种方式创建过滤器但是所有时间都有这个错误,怎么做?

1试试

Vue.filter('onlyNumbers',function (value) {

    return +value.replace(/[^\d.]/g, '');

}); 

2尝试

 export default {
    name: "profile-add-inputs",
    props: ['category'],
    data() {
        return {
            inputs: {
                text : {},
                select: {}
            },
        }
    },
    methods: {
        getCategories(){
         /////
       },
        selectChange(select){
            ///
        },
        inputChange(){
            /// some code what i have
        }
    },
    filters : {
        onlyNumbers: function (value) {

            return +value.replace(/[^\d.]/g, '');

        }
    },
    watch: {
        category : function () {
            this.getCategories();
        },
    }
}

但我总是遇到这个错误

我的错误是add.js:32380 [Vue警告]:属性或方法&#34; onlyNumbers&#34;未在实例上定义,但在呈现期间引用。通过初始化属性,确保此属性在数据选项或基于类的组件中是被动的

2 个答案:

答案 0 :(得分:0)

  

请参阅this以获取有关过滤器不起作用的详细信息。

     

然后参考this了解如何使用双向过滤器

答案 1 :(得分:0)

另一种选择是验证onchange事件的输入

我为您的代码修改了一些工作示例:https://codesandbox.io/s/4rr9nv1p70

您可以在文件App.vue

中找到它