vue-cli进阶使用vuex(配合axios)

首先这不是一篇很正经的博客,这个只是我在项目实际中使用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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值