VueX的使用
Vuex适用于多个子路由,子组件之间传参,如果程序简单,可以使用eventbus
1、VueX文件
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { gradeId: "", subjectId: "", }, mutations: { setgradeid (state, value) { state.gradeId = value; }, setsubjectid (state, value) { state.subjectId = value; } }, actions: { setGradeId (context, value) { context.commit('setgradeid', value) }, setSubjectid (context, value) { context.commit('setsubjectid', value) } } })
2、引入Vuex,main.js文件
import store from './store' new Vue({ router, store, render: h => h(App) }).$mount('#app')
3、设置Vuex的值
getSubject: function (value) { this.nowSubject = value; this.$store.dispatch('setSubjectid', value); }
4、读取VueX的值&监控VueX值的变化
this.$store.state.gradeId
computed: { getgradeId() { return this.$store.state.gradeId; }, getsubjectId() { return this.$store.state.subjectId; }, }, watch: { //如果路由发生了变化,更新页面数据 $route(to, from) { if (to.path !== from.path) { this.schoolID = this.$route.params.id; } }, getgradeId(val) { this.gradeId = val ? val : 0; this.init(); }, getsubjectId(val) { this.subjectId = val ? val : 0; this.init(); }, },