vue 关于Vue使用watch监听属性报“TypeError: Cannot read properties of undefined (reading ‘xxx‘)“的问题

报错信息

Error in callback for immediate watcher “abc”: "TypeError: Cannot read properties of undefined (reading ‘xxx’)"

解决方法:

1、watch当中的方法名写错

错误写法:

watch: {
    $route: {
        immediate: true,
        headler() {  //  这里写错啦!
            console.log(111);
        },
    },
}

正确写法:

watch: {
    $route: {
        immediate: true,
        handler() {
            console.log(111);
        },
    },
}
2、当使用this指向data时报错(使用普通函数)

错误写法:

$route: {
	immediate: true,
	handler: (route) => {
		console.log(this.route);
	},
},

正确写法:

$route: {
   immediate: true,
   handler: function (route) {
       console.log(this.route);
   },
}