npm install vuex --save
- state,驱动应用的数据源;
- view,以声明方式将state映射到视图;
- actions,响应在view上的用户输入导致的状态变化。
store/index.js
import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)const state = { userList: [1, 2, 3, 4], count: 0}const getters = { getUrlParams: () => () => { let url = location.search; let theRequest = {}; if (url.indexOf("?") != -1) { var str = url.substr(1), strs; strs = str.split("&"); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]); } } return theRequest; }, getUserList: (state) => { //注:这里会缓存,只有执行了 actions,这里的缓存才会更新 return state.userList; }}const mutations = { setUserList(state, data){ // 如果这里的 userList 接口返回,可以用axios请求 state.userList=data; }, mutationsAddCount(state, n = 0) { return (state.count += n) }, mutationsReduceCount(state, n = 0) { console.log(n) return (state.count -= n) }}const actions={ actionsAddCount(context, n = 0) { console.log(context) return context.commit('mutationsAddCount', n) }, actionsReduceCount({ commit }, n = 0) { return commit('mutationsReduceCount', n) }, commitUserList:({commit}, userList) => commit('setUserList',userList)}// const actions = {// commitUserList: ({ commit }, userList) => commit('setUserList', userList)// }const store = new Vuex.Store({ state: state, getters: getters, mutations: mutations, actions: actions})export default store;
demo:
,
- { {index}}----{ {user}}
demo2:
{ {$store.state.count}}
https://www.jianshu.com/p/f393bdd3b03d