vue在项目搭建axios流程和吧api挂载到原型
- 安装axios
在命令行中执行以下命令:
npm install axios
- 创建一个axios实例
在项目的src目录下创建一个api文件夹,并在其中创建一个axios.js文件,用于创建一个axios实例:
import axios from 'axios'
const instance = axios.create({
baseURL: 'https://api.example.com'
})
export default instance
在实例中设置了baseURL,表示所有请求的url都会以此为前缀。
- 在组件中使用axios
在需要使用axios的组件中,可以引入刚才创建的axios实例,并使用它发送请求:
import axios from '@/api/axios'
export default {
data () {
return {
users: []
}
},
mounted () {
axios.get('/users')
.then(response => {
this.users = response.data
})
.catch(error => {
console.log(error)
})
}
}
在上述代码中,通过调用axios实例的get方法,发送了一个请求,并在请求成功后将返回的数据赋值给组件的data属性中的users数组。
- 将axios挂载到Vue原型上
为了在组件中更方便地使用axios,可以将axios实例挂载到Vue的原型上。在项目的main.js文件中添加如下代码:
import axios from '@/api/axios'
Vue.prototype.$http = axios
这样,在任何组件中,就可以通过this.$http来访问axios实例。例如:
export default {
methods: {
getUsers () {
this.$http.get('/users')
.then(response => {
this.users = response.data
})
.catch(error => {
console.log(error)
})
}
}
}
在上述代码中,使用了this.$http来访问axios实例,并发送了一个get请求。
原文地址: https://www.cveoy.top/t/topic/0uG 著作权归作者所有。请勿转载和采集!