如何从手表调用功能?

vue.js Vue.js

LEY老丝

2020-03-12

data: function ()  {
    return {
       questions: []
    }
},

watch: {
    questions : function(val, oldVal) {
        foo()
    }
},      

methods: {
    foo() {
        console.log("foo called");
    }
}

产生错误: ReferenceError: foo is not defined

我也在看示例:http : //vuejs-ru.github.io/vuejs.org/api/options.html#watch

这个字符串做什么?

handler: function (val, oldVal) { /* ... */ }, handler是关键字吗?还是可以起作用?

第1313篇《如何从手表调用功能?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
Tony达蒙Mandy 2020.03.12

如果要使用watch观察属性,可以使用this.foo以下方法调用它

data: function ()  {
    return {
       questions: []
    }
},

watch: {
    questions: {
        handler: function(val, oldVal) {
            this.foo(); // call it in the context of your component object
        },
        deep: true
    }
},      

methods: {
    foo() {
        console.log("foo called");
    }
}

回答关于的问题handler:这是一个关键字属性,可以使用函数表达式(如示例中)或对函数的引用,例如:

function myHandler() { ... } // Defined somewhere outside of the vue component object

...

handler: myHandler,

...

出于好奇:您是否需要监视属性才能在每次更改时执行某项操作,或者计算出的属性也可以解决您的问题?

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android