1. 程式人生 > >vue.js之【vuex】

vue.js之【vuex】

state 一個 流程控制 rem ise 導出 pre sync ati

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】