问题描述
页面跳转后,变化menu
的激活状态
现在存在的问题效果
我改变了对应的路径,但是menu
的激活状态没有及时更新
解决方法
1.vuex中定义属性+同步方法+异步方法
import Vue from 'vue'
import Vuex from "vuex"
Vue.use(Vuex);
export default new Vuex.Store({
//定义全局使用的数据 接收数据:
state: {
activePath: '/index',
},
mutations: {
changActivePath(state, activePath) {
state.activePath = activePath
},
actions: {
//在actions中,不能直接修改state里面的数据;
//必须通过context.commit()触发某个mutation才行
//触发action 如下: //this.$store.dispatch('changActivePath','值');
changActivePathAsync(context, activePath) {
context.commit('changActivePath', activePath)
},
},
},
})
- 在
state
中定义属性activePath
- 在
mutations
中定义 异步方法changActivePathAsync
- 在
actions
中定义 同步方法changActivePath
在 mutations 中
context.commit
的值必须和上面的 actions 一致
2.绑定 计算属性(computed)
computed: {
testActivePath() {
if (this.$store.state.activePath === '/groupDetail') {
console.log('不会消失?')
return '/group'
}
return '/index'
},
},
这个判断当然是不全的,需要对所有路由进行判断,要去写一个函数
上方的menu 绑定计算属性
因为
menu
动态绑定上vuex
的值,必须要将属性定义在 **computed
** 中
<el-menu
:default-active="testActivePath"
mode="horizontal"
background-color="white"
>
<el-menu-item
v-for="(subItem, key) in menulist"
:index="'/' + subItem.path"
:key="subItem.id"
@click="saveNavState('/' + subItem.path)"
>
{{ subItem.menuName }}
</el-menu-item>
</el-menu>
3.在点击时修改
①click绑定函数 saveNavState
,函数中修改值
this.$store.dispatch('changActivePathAsync', activePath)
②在跳转的时候修改
this.$router.push({
path: '/groupDetail/' + row.userGroupId,
})
this.$store.dispatch('changActivePathAsync', "/groupDetail")
当然,对于所有的跳转都需要作处理,这里只对一个进行展示
最终实现效果