1. 程式人生 > 程式設計 >vue中全域性路由守衛中替代this操作(this.$store/this.$vux)

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',template: '<App/>'
})
router.beforeEach((to,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)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。