Home > Article > Web Front-end > How to implement global registration in axios
This article mainly introduces you to the relevant information about how to register axios globally. The article introduces it in detail through sample code. It has certain reference learning value for everyone to learn or use axios. Friends who need it can learn together. Bar.
Preface
When I wrote a project using Vue recently, I used axios, because axios cannot use Vue.use() (details can be introduced (Refer to this article), so you need to import when using axios in each .vue file. If there are few .vue files, it will be fine, but if there are many, it will be a bit troublesome.
Later I thought about whether I could add axios directly to the Vue prototype, so that global registration would be achieved. Not much to say below, let’s take a look at the detailed introduction.
The method is as follows:
1. First introduce axios
import Vue from 'vue' import axios from 'axios' //把 `axios` 加到 `Vue` 的原型中 Vue.prototype.axios = axios; new Vue({ el: '#app', render:h => h(App) })
in main.js 2. When using it in a .vue file, pay attention to adding this
<script> export default { name:'app', data(){ return{ msg:'hello' } }, methods:{ send(){ // 注意:因为 axios 是加到 Vue 的原型中了,所以使用 axios 方法时,前面需要加 this this.axios.get('https://www.baidu.com*******') .then(resp => { console.log(resp.data) }).catch(err => { console.log(err); }) } } } </script>
before axios. The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to build helloWorld using vue-cli in vue
Issues related to value passing in layui
How to implement a lottery system using JavaScript
Detailed answer: What impact do changes in vue have on components?
Detailed explanation of how to configure Vue packaging tool
The above is the detailed content of How to implement global registration in axios. For more information, please follow other related articles on the PHP Chinese website!