美文网首页
How to use axios with vue.js 2.0

How to use axios with vue.js 2.0

作者: ccphantom | 来源:发表于2017-07-23 10:26 被阅读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')
    }
}

相关文章

网友评论

      本文标题:How to use axios with vue.js 2.0

      本文链接:https://www.haomeiwen.com/subject/qwipkxtx.html