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:
,<template> <div id="demo54"> <ul> <li v-for="(user,index) in userList" :key="index">{{index}}----{{user}}</li> </ul> <button @click="updateUserList()">更新用户列表</button> </div> </template> <script> export default { data() { return { userList: this.$store.getters.getUserList //引入state中的对象 }; }, methods: { updateUserList () { var item = ["a", "b", "c", "d"]; this.$store.dispatch('setUserList', item); } } }; </script> <style> </style>
demo2:
<template> <div class="demo55"> <h3>{{$store.state.count}}</h3> <button @click="handleAddClick(10)">增加</button> <button @click="handReduceClick(10)">减少</button> </div> </template> <script> export default { data() { return {}; }, methods: { handleAddClick(n) { this.$store.commit("mutationsAddCount",n) }, handReduceClick(n) { this.$store.commit("mutationsReduceCount", n); } } }; </script>
https://www.jianshu.com/p/f393bdd3b03d