VueJs 上的 $route 监视函数内的组件范围不正确
Incorrect component scope inside a $route watch function on VueJs
所有。
我正在开发一个应用程序,我需要根据应用程序路由路径 load/change 数据。
要知道 url 何时更改,我向 $route
添加了一个 watch
函数,我想在同一组件中调用一个函数来加载数据,所有的工作唯一的是 watch
函数内的 this
的范围而不是引用 VueComponent 实例正在返回另一个对象。
这是我的简化代码来获得一个想法
component.vue
<template>
<div id="lists">
{{pageTitle}}
</div>
</template>
<script>
export default {
name: 'lists',
data() {
return {
pageTitle: 'Some Title',
};
},
created() {
console.log('LOAD THE ASKED PATH');
console.log(this.$route.params); /* Object */
console.log(this); /* VueComponent Instance */
},
watch: {
$route: (value) => {
console.log('ROUTE CHANGED');
console.log(value); /* Route Object */
console.log(this); /* NOT A VueComponent */
this.pageTitle = 'Some new title';
},
},
};
</script>
这是我在 watch
函数
中为 this
得到的对象
{default: {…}, __esModule: true}
default : beforeCreate : [ƒ]
beforeDestroy : [ƒ]
created : ƒ created()
data : ƒ data()
name : "lists"
render : ƒ ()
staticRenderFns : []
watch : {$route: ƒ}
_Ctor : {0: ƒ}
__file : "../my-app/src/components/Lists.vue"
__proto__ : Object
不确定这种方法是否正确或我遗漏了什么。
任何帮助将不胜感激。
提前致谢。
不要使用箭头函数来定义监视处理程序(或方法、计算值或生命周期方法等)。箭头函数按词法绑定 this
,并且不能重新绑定。
相反,只需使用常规函数即可。 Vue 会将其绑定到 Vue。
watch:{
$route: function(value){
console.log('ROUTE CHANGED');
console.log(value); /* Route Object */
console.log(this); /* NOT A VueComponent */
this.pageTitle = 'Some new title';
}
},
所有。
我正在开发一个应用程序,我需要根据应用程序路由路径 load/change 数据。
要知道 url 何时更改,我向 $route
添加了一个 watch
函数,我想在同一组件中调用一个函数来加载数据,所有的工作唯一的是 watch
函数内的 this
的范围而不是引用 VueComponent 实例正在返回另一个对象。
这是我的简化代码来获得一个想法
component.vue
<template>
<div id="lists">
{{pageTitle}}
</div>
</template>
<script>
export default {
name: 'lists',
data() {
return {
pageTitle: 'Some Title',
};
},
created() {
console.log('LOAD THE ASKED PATH');
console.log(this.$route.params); /* Object */
console.log(this); /* VueComponent Instance */
},
watch: {
$route: (value) => {
console.log('ROUTE CHANGED');
console.log(value); /* Route Object */
console.log(this); /* NOT A VueComponent */
this.pageTitle = 'Some new title';
},
},
};
</script>
这是我在 watch
函数
this
得到的对象
{default: {…}, __esModule: true}
default : beforeCreate : [ƒ]
beforeDestroy : [ƒ]
created : ƒ created()
data : ƒ data()
name : "lists"
render : ƒ ()
staticRenderFns : []
watch : {$route: ƒ}
_Ctor : {0: ƒ}
__file : "../my-app/src/components/Lists.vue"
__proto__ : Object
不确定这种方法是否正确或我遗漏了什么。
任何帮助将不胜感激。
提前致谢。
不要使用箭头函数来定义监视处理程序(或方法、计算值或生命周期方法等)。箭头函数按词法绑定 this
,并且不能重新绑定。
相反,只需使用常规函数即可。 Vue 会将其绑定到 Vue。
watch:{
$route: function(value){
console.log('ROUTE CHANGED');
console.log(value); /* Route Object */
console.log(this); /* NOT A VueComponent */
this.pageTitle = 'Some new title';
}
},