1、axios的安装 npm install axios --save-dev
2、在需要请求的页面上引入axios
import axios from 'axios'
3、js中的代码必写代码如下 ?
export default {
name: 'HelloData',
data () {
return {
swiperList: [] //需要引入的数据
}
},
methods: {
getHomeInfo () {
axios.get('/static/mock/index.json') //注意路径
.then(this.getHomeInfoSucc)
},
getHomeInfoSucc (res) {
console.log(res)
res = res.data
if (res.ret && res.data) {
const data = res.data
this.swiperList = data.swiperList
}
}
},
mounted () {
this.getHomeInfo()
}
}
</script>
其实可以有更方便的方法:
在created生命周期函数中直接进行后台数据的数据
created () { axios.get('/static/mock/data.json').then((res) => { res = res.data if (res) { console.log(res) 可以获取后台数据 } }) },
需要注意的是 ?
- 这个数据是本地文件下面的虚拟的数据 不希望提交到线上 打开.gitignore 添加一行代码 如下
- 使用的是本地模拟的数据地址 但是代码需要上线 肯定不能填充 /static/mock/index.json 还是需要替换成/api/index.json 使用Proxy代理功能 打开config下面的index.js文件 添加如下代码?
- 完美解决!!!有问题 欢迎来扰!!!
- 来自大三狗子的呕心沥血之作!!!