我有一个组件,该组件是基于活动的路由隐藏的,它启动了一个使用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>发布于 2019-03-10 20:05:37
如果您直接降落在管理页面上,则不会调用您的监视程序,因为$route属性永远不会更改(而且观察者只监视更改)。
您可以做的是在一个方法中移动您的观察者函数,并在created钩子和您的观察者中调用这个方法。
一个更好的方法是使用vue路由器航行警卫。
示例:
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)
},
}https://stackoverflow.com/questions/55045738
复制相似问题