1,npm install vuex --save
2,在src下新建vuex文件夹,新建store.js文件;
store.js
import Vue from ‘vue‘ import Vuex from ‘vuex‘ Vue.use(Vuex) const state = { count: 0, adminleftnavnum:"/" //管理后台左侧导航 } const mutations = { increment (state) { state.count++ } } // const actions = {...} //注册Store export default new Vuex.Store({ state, mutations });
3,在main.js下,创建和挂载根实例
new Vue({ el: ‘#app‘, router, store, template: ‘<App/>‘, components: { App } })
4,在components--common--side_nav.vue下(导航所在的组件)
<el-menu :default-active="navselected" :active="navselected" @select="selectItems" class="el-menu-admin" router>
添加变量和改变方法
export default { components:{ ‘el-menu‘:Menu, ‘el-submenu‘:Submenu, ‘el-menu-item‘:MenuItem, ‘el-menu-item-group‘:MenuItemGroup }, data () { return { navselected:"/", openends:[‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘]//默认menu展开 } }, mounted(){ console.log(this.navselected) }, methods:{ getNavType(){ this.navselected=this.$store.state.adminleftnavnum; //store.state.adminleftnavnum里值变化的时候,设置navselected }, selectItems(index){ console.log(index) this.$store.state.adminleftnavnum=index; //按钮选中之后设置当前的index为store里的值。 } }, watch: { // 监测store.state ‘$store.state.adminleftnavnum‘: ‘getNavType‘ } }
5,在其他组件改变(src--components--page--home--home.vue)
this.$store.state.adminleftnavnum的值即可
export default { created () { this.$store.state.adminleftnavnum="2-2"; //设置左侧导航2-2 active } }
预览地址:https://besswang.github.io/element-admin/dist/index.html#/
参考地址:http://yaohuitao.com/?p=341