码迷,mamicode.com
首页 > 移动开发 > 详细

Vue 使用 Vuex 和 axios 获取接口数据

时间:2019-08-10 13:54:58      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:vue   odi   log   结合   方案   The   main   ext   from   

  1. 修改原型链
//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 结合 axios 封装一个 actions

//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()
    }
    
}

上述两种方案是相互独立的,也就是说,即使在main.js中引入了axios并修改了原型链,
在store.js中也不能直接使用this.$ajax,而是要引入axios后再使用。

Vue 使用 Vuex 和 axios 获取接口数据

标签:vue   odi   log   结合   方案   The   main   ext   from   

原文地址:https://www.cnblogs.com/sakura666/p/11331062.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!