1、合并参数
合并params和query参数
goSearch(){
if (this.$route.query) {
let location = {
name: "Search",
params: { keyword: this.keyword || undefined },
};
location.query = this.$route.query;
this.$router.push(location);
}
}
2、mockjs模拟数据
mockjs插件模拟数据
npm install mockjs
1、项目中创建src/moc文件夹 2、准备json数据(moc文件夹创建响应的json文件) 3、把mock数据放在public文件夹下 4、通过mockjs创建虚拟数据 5、在main.js中引入mockServer.js
src/mockServer.js
import Mock from 'mockjs';
import banner from './banner.json';
import floor from './floor.json';
Mock.mock("/mock/banner",{code:200,data:banner});
Mock.mock("/mock/floor",{code:200,data:floor});
3、在store中存取轮播图数据
灵魂三连环 1、store中的state存储一个数组,因为返回的就是一个数组 2、mutations中修改路逻辑 3、actions中commit数据结果 4、组件(listContainer)中已经携带了bannerList数据 store/home/index.js
import {reqCategoryList,reqGetBannerList} from '../../api'
const state={
categoryList:[],
bannerList:[]
}
const mutations={
CATEGORYLIST(state,categoryList){
state.categoryList=categoryList
},
GETBANNERLIST(state,bannerList){
state.bannerList=bannerList
}
}
const actions={
async categoryList({commit}){
let result=await reqCategoryList()
if(result.code === 200){
commit("CATEGORYLIST",result.data)
}
},
async getBannerList({commit}){
let result=await reqGetBannerList()
if(result.code === 200){
commit("GETBANNERLIST",result.data)
}
}
}
const getters={}
export default {
state,
mutations,
actions,
getters
}
views/home/listContainer
import {mapState} from 'vuex'
export default {
name: 'ListContainer',
mounted () {
this.$store.dispatch('getBannerList')
},
computed:{
...mapState({
bannerList:(state)=>{
return state.home.bannerList
}
})
}
}
</script>
4、使用swiper插件实现轮播图
1、引包(swiper和相应的css) 2、要先有页面结构 3、要new Swiper实例
5、使用watch+$nextTick解决轮播图
<!--banner轮播-->
<div class="swiper-container" id="mySwiper">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="(carousel,index) in bannerList " :key="carousel.id">
<img :src="carousel.imgUrl" />
</div>
</div>
<!-- 如果需要分页器 -->
<div class="swiper-pagination"></div>
<!-- 如果需要导航按钮 -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>
由于没有使用$nextTick(),以下代码是错误的
watch:{
bannerList:{
handler(newValue,preValue){
let mySwiper = new Swiper(document.getElementsByClassName("swiper-container"),{
loop:true,
pagination:{
el: '.swiper-pagination',
clickable: true,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
scrollbar: {
el: '.swiper-scrollbar',
},
})
}
},
使用$nextTick要穿一个回调函数 在下次dom更新循环结束后执行延迟回调,在修改数据之后立即使用这个方法,获取更新后的dom
以下代码是正确的
watch:{
bannerList(newValue,preValue){
this.$nextTick(()=>{
let mySwiper = new Swiper(document.getElementsByClassName("swiper-container"),{
loop:true,
pagination:{
el: '.swiper-pagination',
clickable: true,
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
scrollbar: {
el: '.swiper-scrollbar',
},
})
})
},
}
|