Vue Watch在页面刷新/重新加载时未触发

时间:2019-03-07 14:07:36

标签: vue.js vuex vue-router

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

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

但是,我注意到当我进入经过身份验证的页面(例如管理面板或仪表板等)时,该组件可以正确显示,但是当/如果有人重新加载该网页,该组件就会消失,仅在单击链接时才会显示到另一个页面。

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>

1 个答案:

答案 0 :(得分:0)

如果您直接进入管理页面,则不会调用您的观察者,因为$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)
  },
}