Vue在跳转其他类目出现旧数据的原因以及解决方案(笔记)

原因是使用了list作为数据,然后list被新数据覆盖,造成,应该建立数组缓存解决

原来代码list.vue

<template>

<swiper class="home-swiper" :current="activeIndex" @change="change">

<swiper-item v-for="(item,index) in tab" :key="index" class="swiper-item">

<list-scroll class="list-scroll">

<list-cart :mode="item.mode" v-for="(item,index) in list" :key="item._id" :item="item"></list-cart>

</list-scroll>

</swiper-item>

</swiper>

</template>

<script>

export default {

data() {

return {

list:[]

};

},

mounted() {

this.getList('后端开发')

},

methods:{

change(e){

const current = e.detail.current

this.getList(this.tab[current].name)

this.$emit('change',e.detail.current)

},

getList(name){

this.$api.get_list({name}).then((res)=>{

this.list= res.data

console.log(this.list)

})

}

},

props:{

tab:{

type:Array,

default:[]

},

activeIndex:{

type:Number,

default:0

}

}

}

</script>

<style lang="scss">

.home-swiper {

height: 100%;

.swiper-item{

height: 100%;

overflow: hidden;

.list-scroll{

height: 100%;

}

}

}

</style>


使用listCatchData数组储存data,放在相应的index中


但是由于listCatchData的结构为多层循环数组,Vue未必会侦测到数组数据变化,所以要使用this.$forceUpdate()进行强制刷新

更改后代码

<template>

<swiper class="home-swiper" :current="activeIndex" @change="change">

<swiper-item v-for="(item,index) in tab" :key="index" class="swiper-item">

<list-scroll class="list-scroll">

<list-cart v-for="item in listCatchData[index]" :key="item._id" :mode="item.mode" :item="item"></list-cart>

</list-scroll>

</swiper-item>

</swiper>

</template>

<script>

import listItem from './list-item.vue'

export default {

data() {

return {

list:[],

listCatchData:{},

current:0

};

},

components:{listItem},

watch:{

tab(newVal){

if(newVal.length === 0)return

this.getList(this.tab[this.activeIndex].name)

}

},

methods:{

change(e){

this.current = e.detail.current

this.getList(this.tab[this.current].name)

this.$emit('change',e.detail.current)

},

getList(name){

this.$api.get_list({name}).then((res)=>{

this.listCatchData[this.current] = res.data

console.log(this.listCatchData)

this.$forceUpdate()

//this.$set(this.listCatchData,this.current,res.data)//1需要改变的数组,2修改的第几项,3修改的内容

})

}

},

props:{

tab:{

type:Array,

default:[]

},

activeIndex:{

type:Number,

default:0

}

}

}

</script>

<style lang="scss">

.home-swiper {

height: 100%;

.swiper-item{

height: 100%;

overflow: hidden;

.list-scroll{

height: 100%;

}

}

}

</style>

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。