vue中全局路由守衛中替代this操作(this.$store/this.$vux)
全局路由守衛this.$vux.loading.hide()報錯,訪問不到this
解決辦法
申明變量代替this
main.js文件方法
router.beforeEach((to, from, next) => { if(vue){ vue.$vux.loading.hide() }else{ } next()})let vue = new Vue({ el: ’#app’, router, store, components: { App }, template: ’<App/>’})
if判斷防止第一次初始化報錯
或者
let vue = new Vue({ el: ’#app’, router, store, components: { App }, template: ’<App/>’})router.beforeEach((to, from, next) => { // if(vue){ vue.$vux.loading.hide() // }else{ // } next()})
補充知識:解決導航守衛使用不了this.$store
在vue router的導航守衛如beforeEach()中是無法直接通過this.$store去操作vuex的,因為這里的this指向不一致。
解決方式是在router的index.js中引入初始化好的store
import store from ’@/store’
然后在導航守衛中可直接拿到router了
/**導航守衛 */router.beforeEach((to, form, next) => { console.log(store.getters)})
以上這篇vue中全局路由守衛中替代this操作(this.$store/this.$vux)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: