本文共 3075 字,大约阅读时间需要 10 分钟。
一、初始化
vue init webpack-simple 文件名cd 文件名npm installnpm install vuex -D // 安装vuexnpm run dev
二、在src创建store.js
// 引入vue和vueximport Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex);// state 管理数据const 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) =>{ setTimeout(function() { alert(1); }, 1000); }) }};const getters = { count: state => { return state.count; }, getOdd: state => { return state.count%2 == 0? "偶数": "奇数"; }}export default new Vuex.Store({ state, mutations, actions, getters});
三、main.js引用
import Vue from 'vue'import App from './App.vue'import store from './store'new Vue({ store, el: '#app', render: h => h(App)})
四、App.vue
Welcome vuex
现在的数字为:{ {count}}, 他现在是{ {getOdd}}
官方推荐使用这样的目录结构
|--src |--store |--index.js // |--types.js // state数据 |--mutations.js // mytations |--actions.js // actions |--getter.js // 获取数据
index.js
// 引入vue和vueximport Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex);// 引入actions和mutationsimport actions from './actions'import mutations from './mutations'import getters from './getters'export default new Vuex.Store({ modules: { mutations }, actions, getters})
types.js
export const INCREMENT = 'INCREMENT'export const DECREMENT = 'DECREMENT'
mutations.js
import { INCREMENT, DECREMENT} from './types'const state = { count: 20};const mutations = { [INCREMENT]: (state) => { state.count++; }, [DECREMENT]: (state) => { state.count--; }};export default { state, mutations}
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) }) }}
getter.js
export default { count: (state)=> { return state.count; }, getOdd: (state)=> { return state.count % 2 == 0 ? "偶数": "奇数"; }}
App.vue不用变,只需改动main.js的引用
import store from './store/'