如何在自定义Vue原型中访问类似于this。$ route的$ route对象?
//main.js
Vue.prototype['$notify'] = params => {
//console.log('this', this) undefined
console.log('Vue.prototype', Vue.prototype)
/* console shows among other valid properties:
$route: [Exception: TypeError: Cannot read property '_route' of undefined at Object.get (webpack-internal:///./node_modules/vue-router/dist/vue-router.esm.js:1221:52) at Object.invokeGetter (<anonymous>:2:14)]
$router: [Exception: TypeError: Cannot read property '_router' of undefined at Object.get (webpack-internal:///./node_modules/vue-router/dist
*/
//this throws error: Vue.prototype.$route
}
答案 0 :(得分:1)
箭头功能不是常规功能的捷径,它使用词法this
而不是动态this
是差异之一。
如果该方法应访问Vue实例,则应为:
Vue.prototype['$notify'] = function (params) {
console.log(this.$route);
...
};