Home > Web Front-end > JS Tutorial > Introduction to the method of using axios globally in vue project

Introduction to the method of using axios globally in vue project

不言
Release: 2019-03-20 11:44:35
forward
2859 people have browsed it

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);
Copy after login
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);
});
Copy after login

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
Copy after login

Use in components

this.$http.get('/api/usrmng')
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});
Copy after login

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
Copy after login

When sending a request in the component, you need to use this.$ store.dispatch

methods: {
  submitForm () {
     this.$store.dispatch('login')
  }
}
Copy after login

This article is over here. For more exciting content, you can pay attention to the JavaScript 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!

Related labels:
vue
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template