Vue中使用axios发送ajax请求

时间:2022-03-13 12:03:43

作为前后端交互的重要技巧--发送ajax请求,在Vue中我们使用axio来完成这一需求:

首先是下载axios的依赖,

npm install --save axios vue-axios

然后在main.js中注册全局使用,

import Vue from 'vue'(基本项目建成就有,查看一下之前是否就有写,有的话可以省略)

import axios from 'axios'

import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios) (注:这里划重点,不要管引入顺序,这里的use顺序一定不能变!important)

好了,接下来你就可以在你的项目中发送ajax请求了

Ex:

getStars() {

let url = 'https://api.github.com/search/repositories?q=v&sort=stars'

this.axios.get(url)

.then((res) => {

console.log(res)

})

.catch((err) => {

console.log(err)

})

}

这里请求的书写方式有很多种。大家怎么舒服怎么写

Vue.axios.get()

this.axios.get()

this.$http.get()

或者

getStars(){

let url = 'https://api.github.com/search/repositories?q=v&sort=stars'

this.axios({

method: 'get',

url: url

}).then((res) => {

console.log(res)

})

谢谢~