VUE中使用axios获取http请求数据

首先使用 npm install axios
然后在 main.js 中注册全局环境使用的方法,比如:

import axios from 'axios'
//这时候如果在其它的组件中,是无法使用 axios 命令的。但如果将 axios 改写为 Vue 的原型属性,就能解决这个问题
Vue.prototype.$ajax = axios

在 main.js 中添加了这两行代码之后,就能直接在组件的 methods 中使用 $ajax 命令

this.$ajax.get('data.json').then(function (res) {
    this.data = res.data
}.bind(this))

这两个回调函数都有各自独立的作用域,如果直接在里面访问 this,无法访问到 Vue 实例
这时只要添加一个 .bind(this) 就能解决这个问题

猜你喜欢

转载自blog.csdn.net/xjtarzan/article/details/80040646