Vue Watch 未在页面上触发 Refresh/Reload

Vue Watch not Triggering on Page Refresh/Reload

我有一个基于活动路由隐藏的组件,它启动了一个使用 vuex 存储存储的功能。

它按预期工作,sidenav 在登录、注销和注册时隐藏。

但是,我注意到当我在经过身份验证的页面(例如管理面板或仪表板等)上时,该组件显示正确,但是 when/if 有人重新加载网页,该组件消失了,只能显示单击 link 到另一个页面时。

App.Vue

<template>
    <div id="app">
        <navbar />
        <sidenav v-show="sidenav_toggle" />
        <div class="row router-container">
            <div class="col router-row">

                <router-view/>
            </div>
        </div>
    </div>
</template>
<script>
import Vue from 'vue'
import Vuex from 'vuex'
import router from '@/router'

import axios from 'axios'
import AxiosStorage from 'axios-storage'

let sessionCache = AxiosStorage.getCache('localStorage');



import materializecss from '../static/css/main.css'
import materializejs from '../static/materialize-css/dist/js/materialize.js' 

import navbar from '@/components/navbar'
import sidenav from '@/components/sidenav'

Vue.use(Vuex)

const state = {
    sidenav:{
        show: false
    }
}

const mutations = {
    show_sidenav(state){
        state.sidenav.show = true
    },
    hide_sidenav(state){
        state.sidenav.show = false
    }
}

const store = new Vuex.Store({
    state,
    mutations
})



export default {
    router,
    name: 'App',
    watch:{
        $route: function(){
            if(this.$route.path === '/login' || this.$route.path === '/logout' || this.$route.path === '/register'){
        store.commit('hide_sidenav')
        console.log('not authd')
            }else{
        store.commit('show_sidenav')
        console.log('authd')
            }
        },
        deep: true,
        immediate: true
    },
    computed: {
        sidenav_toggle(){
            return store.state.sidenav.show
        }
    },

    data: function(){
        return{
        }
    },
    components: {
        navbar,
        sidenav
    },
    methods: {


    },
    created: function(){

    }
}
</script>

如果您直接登陆管理页面,您的观察者不会被调用,因为 $route 属性 永远不会改变(并且观察者只会观察变化)。

您可以做的是将观察器函数移动到一个方法中,然后在 created 挂钩和观察器中调用此方法。

一个更好的方法是使用 vue-router navigation-guards

示例:

export default {
  // ...
  methods: {
    adaptSidebar(path) {
      if (['/login', '/logout', '/register'].includes(path)) {
        store.commit('hide_sidenav')
      } else {
        store.commit('show_sidenav')
      }
    },
  },
  beforeRouterEnter(from, to, next) {
    // As stated in the doc, we do not have access to this from here
    next(vm => {
      vm.adaptSidebar(to.path)
    })
  },
  beforeRouteChange(from, to, next) {
    this.adaptSidebar(to.path)
  },
}