工具有三:
浏览器自带的fetch函数
vue-resourse
axios第三方模块(可跨平台)
只有static目录可以被外部工程访问到,把json文件放到static目录下,但是容易被别人获取到,所以在.gitignore
文件中加上static
,项目上线时也不会被别人获取。
使用方法:
npm install axios --save
如果在每个组件中都访问axios的话,请求次数太多就不大好,故而放在Home.vue中就只用请求一次了。
static下新建一个index.json 文件
引用如下:
import axios from 'axios'
methods :{
getHomeInfo () {
axios.get('/api/index.json') //此处使用了代理
.then(this.getHomeInfoSucc)
},
getHomeInfoSucc (res) { //打印出来
console.log(res)
}
},
mounted () {
this.getHomeInfo()
}
在config文件夹的index.js文件proxyTable
下添加 (此处目的为代理,便于上线)
'/api':{
target :'http://localhost:8080',
pathRewrite:{
'^/api': '/static/mock'
}
}
具体使用方法我就直接贴代码啦~
Home.vue文件中:
<--子组件中绑定属性--!>
<home-header :city="city"></home-header>
<home-swiper :swiperList="swiperList"></home-swiper>
<home-icons :iconList="iconList"></home-icons>
<home-recommend :recommendList="recommendList"></home-recommend>
<home-weekend :weekendList="weekendList"></home-weekend>
data () {
return {
city:'',
swiperList:[],
iconList:[],
recommendList:[],
weekendList:[]
}
},methods :{
getHomeInfo () {
axios.get('/api/index.json')
.then(this.getHomeInfoSucc)
},
getHomeInfoSucc (res) {
res=res.data;
if (res.ret && res.data){
const data = res.data;
this.city = data.city
this.swiperList = data.swiperList
this.iconList = data.iconList
this.recommendList = data.recommendList
this.weekendList = data.weekendList
}
}
},
mounted () {
this.getHomeInfo()
}
在子组件中添加props:{ iconList:Array },
属性及属性类型即可。
会出现一个问题,轮播图时会出现一个问题,首先出现的页面是最后一张图片,可添加v-if来判断数组的长度是否为0,若为0则不显示。其长度可用计算属性来表示。
v-if="showSwiper"
computed: {
showSwiper () {
return this.swiperList.length
}
}
出现如下报错:
由于浏览器必须要在执行事件处理函数之后,才能知道有没有掉用过 preventDefault() ,这就导致了浏览器不能及时响应滚动,略有延迟。
[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive.
解决方案在css中添加*{touch-action: none;}