项目结构
-store
-actions
-plan.js
-getters
-modules
-plan.js
-mutations-types
-mutation-types.js
-store.js
-App.vue
-main.js
-目录结构详解
- actions:提供给组件中调用的方法,在该目录下的方法是dispatch给store通知调用方法改变state
- getters:在组件接收store中state时可以进行处理之后再赋值
- modules:用于state和mutations区分开,由于组件的状态和状态的改变全部集中到一个store.js中容易混淆,所以区分开写。然后在store.js中可以使用modules组合成一个。
- mutations-types:用于存储静态的方法名字,在actions中调用之后的type,注:静态变量全部是大写,用于区分action和store中的mutations
- store.js在此集中之前全部的资源,store引用分开的state和mutations,组件调用时引用actions,然后在action调用dispatch,去触发store中的mutations,更新state
- modules:用于state和mutations区分开,由于组件的状态和状态的改变全部集中到一个store.js中容易混淆,所以区分开写。然后在store.js中可以使用modules组合成一个。# Vuex+Vue+Router
store.js内容
/*
页面状态控制主目录
*/
// 基础应用
import Vue from 'vue';
import Vuex from 'vuex';
// 引用部分
import plan from './modules/plan';
// 引用Vue
Vue.use(Vuex);
// 所有状态全部转移到modules中各部分
Vue.config.debug = true;
export default new Vuex.Store({
modules: {plan} // 包括状态和变化方法
});
modules实例内容
/*
plan页面设置
*/
import {OPEN_MODEL, UPDATE_RULENAME} from '../mutation-types/mutation-types';
const state = {
cancelVoucherShow: false,
ruleName: ''
};
const mutations = {
[OPEN_MODEL] (state) {
// 模态框取反
state.cancelVoucherShow = !state.cancelVoucherShow;
},
[UPDATE_RULENAME] (state, ruleName) {
state.ruleName = ruleName.target.value;
console.log(state);
}
};
export default {
state,
mutations
};
mutation-types内容
/**
* Created by YuanGao on 2016/10/18.
*/
// 改变打开模态框状态
export const OPEN_MODEL = 'OPEN_MODEL';
export const UPDATE_RULENAME = 'UPDATE_RULENAME';
在组件内使用
import InputComponent from '../../../../commoncode/inputcomponent.vue';
import dropmenu from '../../../../commoncode/dropmenu.vue';
import datepicker from '../../../../commoncode/datepicker.vue';
import {updateRuleName} from '../../../../../store/actions/plan';
export default {
vuex: {
getters: {
ruleName: ({plan}) => plan.ruleName
},
actions: {
updateRuleName: updateRuleName
}
},
components: {
InputComponent,
dropmenu,
datepicker
},
methods: {
show (tag) {
const s1 = document.getElementById('s1');
const s2 = document.getElementById('s2');
const s3 = document.getElementById('s3');
if (tag === 1) {
s1.style.display = 'block';
s2.style.display = 'none';
s3.style.display = 'none';
} else if (tag === 2) {
s2.style.display = 'block';
s1.style.display = 'none';
s3.style.display = 'none';
} else if (tag === 3) {
s3.style.display = 'block';
s1.style.display = 'none';
s2.style.display = 'none';
} else if (tag === 0) {
s1.style.display = 'none';
s2.style.display = 'none';
s3.style.display = 'none';
}
}
}