Vue Vuex use interface data acquisition and axios

  1. Modify the prototype chain
//main.js

import axios from 'axios';

Vue.prototype.$ajax = axios; //修改原型链

// .vue文件

methods:{
    getData(){
        this.$ajax.get('https://easy-mock.com/mock/5d41481656e5d340d0338e4b/shop/commodity')
            .then(res => {
                console.log(res)
            }).catch(err => {
                console.log(err)
            })
    }
}

2.Vuex a package combined actions axios

//store.js

import Vue from 'vue';
import Vuex from 'Vuex';
import axios from 'axios';

export const store = new Vuex.Store({
    State: {
        list: []
    },
    mutations: {
        changeList(state,res){   // store中的数据只能通过commit mutation来改变
            state.list = res.data.data.list
        }
    },
    actions: {
        getInfo(context) {
            axios.get('https://easy-mock.com/mock/5d41481656e5d340d0338e4b/shop/commodity')
                .then(res => {
                    context.commit('changeList',res)
                }).catch(err => {
                    console.log(err)
                })
        }
    }
})

// .vue文件

import {mapState,mapActions} from 'vuex'

export default {
    name:"HelloWorld",
    methods:{
        ...mapActions([
            'getInfo'   // 触发actions里的 getInfo 函数,调动接口
        ])
    },
    computed:{
        ...mapState([
            'list'      // 获取store里的数据,放在computed中可以实时更新
        ])
    },
    mounted() {
        this.getInfo()
    }
    
}

Both programs are independent of each other, that is to say, even in the axios main.js introduced and modified the prototype chain,
it can not be used directly in this store.js in. $ Ajax, but to use before the introduction of axios .

Guess you like

Origin www.cnblogs.com/sakura666/p/11331062.html