首先这不是一篇很正经的博客,这个只是我在项目实际中使用vuex的一些做法,不过其实做的不是很彻底,因为我没有彻底分离action
,getter
……。
前面其实也写了一下简单实用vuex
的,不过我觉得原来的不适合运用在正经项目中,所以就把那篇作为一个入门基础文:vue-cli简单实用vuex
这里还要配合一下:vue-cli封装axios,因为我引入的文件就是这里的
配置
src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';
import api from '@/request/api' // 导入api接口
Vue.use(Vuex);
let store = new Vuex.Store({
// 1. state
state: {
org: [],
},
// // 2. getters
getters: {
// 参数列表state指的是state数据
//获取组织
getOrgFn(state) {
return state.org;
},
},
// 3. actions
// 通常跟api接口打交道
actions: {
// 参数列表:{commit, state}
// state指的是state数据
// commit调用mutations的方法
// name就是调用此方法时要传的参数
// 设置组织
setOrg({
commit,
state
},
params) {
api.org.query(params).then(res = >{
if (res.data.status == "600") {
commit('setOrg', res.data.data.records)
}
});
},
/*自定义修改数据
setOrg({
commit,
state
},
list) {
commit('setOrg',list))
},
*/
},
// 4. mutations
mutations: {
// state指的是state的数据
//设置组织
setOrg(state, list) {
state.org = list;
},
}
});
这里就比原先多了一个获取数据和设置数据转接口。
使用
src/main.js
import store from './store/index';
new Vue({
el: '#app',
router,
store,
components: {
App
},
template: '<App/>'
})
vue
methods:{
queryOrg(params) {
this.$store.dispatch("setOrg")
/*自定义获取数据
const _this = this;
this.$api.org.query(params).then(res = >{
if (res.data.status == "600") {
_this.$store.dispatch("setOrg",res.data.data.records)
}
});
*/
},
}
created() {
//获取全部客户数据
this.queryOrg();
},
computed: {
//客户数据
orgData() {
return this.$store.getters.getOrgFn;
},
}
不过我这里是数据接口放在action
里面了,还有一种就是自己在方法里面获取到了数据再去commit