首页 > 代码库 > vue.js之【vuex】

vue.js之【vuex】

vuex

合在一起写Vuex.Store

目录结构:

  | src

    | store.js

引入:

import Vue from ‘vue‘
import Vuex from ‘vuex‘

使用vuex

Vue.use(Vuex);

定义一个state

var state = {
	count: 10
};

mutations

const mutations = {
	increment(state) { //处理状态(数据)变化
		state.count++;
	},
	decrement(state) {
		state.count--;
	}
};

actions:

const actions = {
	increment: ({ //处理你要干什么,异步请求,判断,流程控制
		commit
	}) => {
		commit(‘increment‘)
	},
	decrement: ({
		commit
	}) => {
		commit(‘decrement‘);
	},
	clickOdd: ({
		commit,
		state
	}) => {
		if (state.count % 2 == 0) {
			commit(‘increment‘)
		}
	},
	clickAsync: ({
		commit
	}) => {
		new Promise((resolve) => { //Promise异步
			setTimeout(function() {
				commit(‘increment‘);

				resolve();
			}, 1000);
		});
	}
};

getters

const getters = {
	count(state) {
		return state.count;
	},
	getOdd(state) {
		return state.count % 2 == 0 ? ‘偶数‘ : ‘奇数‘;
	}
};

需要导出Store对象

export default new Vuex.Store({
	state,
	mutations,
	actions,
	getters
});

 


将vuex拆分开来写

目录结构:

  |src

    |store

      | index.js

      | actions.js

      | mutations.js

      | types.js

      | getters.js

 

vue.js之【vuex】