Javascript 如何在Vue watch中使用模型?

Javascript 如何在Vue watch中使用模型?,javascript,vue.js,vuejs2,vue-component,Javascript,Vue.js,Vuejs2,Vue Component,我有一个简单的Vue组件,如下所示: export default { data: function () { return { brands: [], models: [ {id:1, name: 'one'}, {id:2, name: 'two'}, {id:3, name: 'tree'} ],

我有一个简单的Vue组件,如下所示:

export default {
    data: function () {
        return {
            brands: [],
            models: [
                {id:1, name: 'one'},
                {id:2, name: 'two'},
                {id:3, name: 'tree'}
            ],

            filters: {},

            filter: {
                brand: null,
                model: null,
                price: null,
                year: null
            }
        }
    },
    watch: {
        'filter.brand': (brand) => {
            console.log('filter.brand', this, this.models)

            socket.emit('brands.models.get', brand, (models) => {
                console.log(models)

                console.log(this.models)

                this.models = models;

                console.log(this.models)
            })
        },
    }
}
主要问题是,当我从套接字接收数据时,我看不到模型

例如
console.log(this.models)
返回未定义的

以下是完整打印的内容:


您应该尝试为观察者使用正常功能:

 'filter.brand': function(){}
因为箭头函数:[(brand)=>{}]没有自己的“this”,我猜这就是问题的根源

PS:为了正常工作,您的代码应该是这样的:

   'filter.brand': function(brand){
        //Access to the vue instance
        var me = this;

        socket.emit('brands.models.get', brand, (models) => {
            me.models = models;
        })
    },
您还可以使用Vue
created()
mounted()
方法,参见

从ECMAScript 2015开始,介绍了对象初始值设定项上方法定义的较短语法

created(){
this.filter.brand='f'
},
观察:{
“过滤器.品牌”(品牌){
log('filter.brand',this,this.models)
},
}
例如