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
App.vue
<template> <div id="app"> <input type="button" value="增加" @click="increment"> <input type="button" value="减少" @click="decrement"> <input type="button" value="偶数才能点击+" @click="clickOdd"> <input type="button" value="点击异步" @click="clickAsync"> {{count}} {{getOdd}} </div> </template> <script> import {mapGetters, mapActions} from 'vuex' export default{ computed:mapGetters([ 'count', 'getOdd' ]), methods:mapActions([ 'increment', 'decrement', 'clickOdd', 'clickAsync' ]) } </script>
main.js
import store from './store/' new Vue({ store, el: '#app', render: h => h(App) })
index.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); import mutations from './mutations' import actions from './actions' export default new Vuex.Store({ modules:{ mutations }, actions });
actions.js
import * as types from './types' export default { increment: ({ commit }) => { commit(types.INCREMENT); }, decrement: ({ commit }) => { commit(types.DECREMENT); }, clickOdd: ({ commit, state }) => { if (state.mutations.count % 2 == 0) { commit(types.INCREMENT); } }, clickAsync: ({ commit }) => { new Promise((resolve) => { setTimeout(function() { commit(types.INCREMENT); }, 1000); }) } }
mutations.js
import { INCREMENT, DECREMENT } from './types' import getters from './getters' const state = { count: 20 }; const mutations = { [INCREMENT](state) { state.count++; }, [DECREMENT](state) { state.count--; } }; export default { state, mutations, getters }
types.js
export const INCREMENT = 'INCREMENT'; export const DECREMENT = 'DECREMENT';
getters.js
export default { count: (state) => { return state.count; }, getOdd: (state) => { return state.count % 2 == 0 ? '偶数' : '奇数' } }
一 state
1.state是唯一的数据源。
2.单一的状态树。
二 getters
1.通过getter可以派生出一些新的状态。
mutations
1.更改vuex的store中的状态的唯一方法是提交mutation。
四,actions
1.action提交的是mutation,而不是直接变更状态。
2.action可以包含任意异步状态。
五.Modules
面对复杂的应用程序,当管理的状态比较多时,我们需要将vuex的store对象分割成模块(modules)。