vue的版本是2,使用插件composition-api尝试组合式api
1. this和this.$router这个方法在setup()里直接使用竟然是undefined
我是这么写的
setup() {
console.log(this)//undefined
console.log(this.$router)//error
}
控制台告诉我显然有问题,但是我在另一个完成的vue页面里在setup()的方法里使用了this.$router,发现可以正常使用
setup() {
function routeBack() {
this.$router.go(-1)
console.log(this.$router)
}
}
这是为什么呢?
当我在setup函数后,接上mounted(),发现this指向的函数又回来了
setup(){
//...
},
mounted() {
console.log(this)
console.log(this.$router)
}
仔细想了下,在setup()直接使用相当于在created和oncreated时调用,此时this的值还没被挂载,应当就是undefined.但是第二段代码为什么生效呢?因为此时this已经被挂载,可以在函数中使用。
所以大家在尝试这个插件的时候,需要注意。
或许直接使用vue3.0和router就不需要这么麻烦啦。