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')
}
}
网友评论