【问题标题】:Vue Watch not Triggering on Page Refresh/ReloadVue Watch 不会在页面刷新/重新加载时触发
【发布时间】:2019-07-29 10:54:32
【问题描述】:

我有一个基于活动路由隐藏的组件,它启动了一个使用 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>

【问题讨论】:

    标签: vue.js vuex vue-router


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-01-18
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 2016-06-26
      • 2020-01-02
      • 2018-08-26
      • 2010-12-24
      相关资源
      最近更新 更多