Home>Article>Web Front-end> Introduction to the method of using axios globally in vue project
This article brings you an introduction to the method of using axios globally in the Vue project. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
There are three methods:
1. Combined with vue-axios
First reference
import axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios,axios);in the main entry file main.js
After that, you can use it in the methods in the component file
this.axios.get('/api/usrmng') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
2. axios is rewritten as the prototype attribute of Vue
First referenced in the main entry file main.js, and then hung on the prototype chain of vue
import axios from 'axios' Vue.prototype.$http = axios
Use in components
this.$http.get('/api/usrmng') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
3. Combine with Vuex action
Referenced in the vuex warehouse file store.js, use the action to add the method
import Vue from 'Vue' import Vuex from 'vuex' import axios from 'axios' Vue.use(Vuex) const store = new Vuex.Store({ // 定义状态 state: { user: { name: 'root' } }, actions: { // 封装一个 ajax 方法 login (context) { axios({ method: 'post', url: '/user', data: context.state.user }) } } }) export default store
When sending a request in the component, you need to use this.$ store.dispatch
methods: { submitForm () { this.$store.dispatch('login') } }
This article is over here. For more exciting content, you can pay attention to theJavaScript tutorial video on the PHP Chinese website.Column!
The above is the detailed content of Introduction to the method of using axios globally in vue project. For more information, please follow other related articles on the PHP Chinese website!