vuex大家都知道是专门为Vue.js应用程序开发的状态管理模式。其实就是一个对于前端开发来说数据仓库
个人经验:action是用来做异步请求,然后把请求回来的数据交给mutation来更新state。
安装
npm i vuex -S
引用
第一步:在main.js同级目录下创建store文件夹
第二步:在store/index.js组装模块并导出
// store/index
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
import user from './modules/user'
import "babel-polyfill" // 兼容IE9及以上版本浏览器
Vue.use(Vuex)
export default new Vuex.Store({
state,
mutations,
actions,
getters,
modules: {
user,
},
strict: debug
});
第三步:在store/index.js组装模块并导出
// 根级别的state.js定义test状态
export default {
test: 'hello world!'
}
import api from '@/api/'//axios接口
// 在根级别的action.js调用异步请求获取服务器端数据传给mutations处理
export default {
getTest: ({commit}, newVal) => {
// commit('setTest', newVal)
api.test(newVal).then(res => {
commit('setTest', res);
})
}
}
// 在根级别的mutations.js进行更新异步数据到本地状态
export default {
setTest(state, newVal) {
state.test = newVal;
}
}
第四步:在store/modules的模块范例user.js
import api from '@/api/'//axios接口
const state = {
test: '用户模块里的test状态'
}
const getters = {
}
const mutations = {
setTest(state, newVal) {
state.test = newVal
}
}
const actions = {
getTest({commit}, param){
// 情景一:
// commit('setTest', param)
// return data;
// 情景二:把异步返回的数据通过mutations更新本地
api.test(param).then(res => {
commit('setTest', res);
})
// 情景三:直接执行异步请求,组件调用时有回调promise
// return api.test(param);
}
}
export default {
namespaced: true, //模块里状态/方法不会出现重名
state,
getters,
mutations,
actions,
}
知识点:设置namespaced: true后,vue组建中调用store
我们都知道通过设置namespacing:true对状态分隔模块管理是必须的,因为他可以避免仓库里的mutations,actions,getters不重名。
用法:
state调用时:
this.$store.state.user.test;
// 或
this.$store.state['user/test'];
getters调用时:
this.$store.getters['user/getTest'];
mutations调用时:
this.$store.commit('user/setTest','sth');
actions调用时:
this.$store.dispatch('user/getTest','sth');
第五步:把vuex的项目结构准备好,开始在main.js入口文件注册到vue上
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store' //引入vuex本地状态管理数据仓库
Vue.use(ElementUI);
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>',
})