How to use axios with vue.js 2.0

When we use vue plugin, we can import the plugin in main.js, and use Vue.use() to register the plugin to vue instance, but unfortunately, axios is not vue plugin, so we can't use Vue.use() to register axios to vue instance, we need to import axios in each component which wants to send HTTP request.
There are two solutions to solve this problem. The first solution is to modify vue prototype after import axios. The second is to create an action to send HTTP request using Vuex.

1. install axios

npm install axios --save

2. Solution 1: Modify Vue prototype

2.1 Import axios in main.js

import axios from 'axios'

2.2 Modify Vue prototype

Vue.prototype.$http = axios

2.3 Create Vue instance

new Vue({
    el:'#app',
})

After modify vue prototype in main.js, you can use this.$http.get() directly in the component which you want to send HTTP request. For exemple:

methods: {
    getData() {
        this.$http.get('url').then(function(response) {
            // success call back
        }).catch(function(error) {
            // error callback
        });
    }
}

3. Solution 2: Using Vuex to create action

create action in store/index.js:

// index.js
import Vue from 'Vue'
import Vuex from 'vuex'
 
// import axios
import axios from 'axios'
 
Vue.use(Vuex)
 
const store = new Vuex.Store({
    // define state
    state: {
        test01: {
            name: 'Wise Wrong'
        },
        test02: {
            tell: '12312345678'
        }
    },
    actions: {
        // create a ajax action
        saveForm (context) {
            axios({
                method: 'post',
                url: '/user',
                data: context.state.test02
            })
        }
    }
})
 
export default store

When you want to send HTTP request in some component, you can use this.$store.dispatch('saveForm') to dispatch the action.

methods: {
    submitForm () {
        this.$store.dispatch('saveForm')
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 英文文档,一开始我也是抗拒的,边翻译边看,也就花费了1个小时基本就阅读过了,我的英文基础其实很差。附上链接:链接:...
    lonecolonel阅读 10,429评论 3 1
  • Awesome Ruby Toolbox Awesome A collection of awesome Ruby...
    debbbbie阅读 3,101评论 0 3
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,996评论 0 0
  • 【作为一个生活在北京的人,我已经热乎乎地感受到今后五年之内,北京将要发生的五个巨变】2017-2-28 07:3...
    星也的简书阅读 334评论 0 0
  • 2017、周四、6、15、晴 今天早上,第二节是体育课,老师叫我们比赛跑步,一个一...
    世界如此美妙阅读 198评论 0 0

友情链接更多精彩内容