2023年5月14日
vue中如何刷新子组件,重置组件,重新加载子组件
项目场景:
在父组件循环数据列表中,列表中有事件点击打开某个子组件;
父组件中要更新子组件的值
问题描述
在父组件循环数据列表中,点击打开某个子组件,A数据打开子组件后,B数据再打开子组件,此时子组件中会有缓存A数据。
原因分析:
子组件没有刷新,还是停留在上一个数据缓存
解决方案:
给组件添加key值
原理:key值变化之后,会自动重新渲染组件
vue中的key的作用主要是为了高效的更新dom, 它也可以用于强制替换元素/组件而不是重复使用它,完成的触发组件的生命周期钩子,触发过渡。
<template>
<el-button @click="btnEvent">刷新子组件</el-button>
<child :key="datekey"></child>
</template>
<script>
export default{
data(){
return {
datekey:Date.now()
}
},
methods:{
btnEvent(){
//这里更新了datekey ,组件就会刷新
this.datekey = Date.now()
}
}
}
</script>
uniapp刷新子组件的方法
v通过-if 在父组件中的onShow 创建和 onHide销毁组件父组件
html <stock :obj=”obj” v-if=”flag” />
js
onShow() {
this.flag = true
},
onHide() {
this.flag = false
},
Haave youu ever thought about addig a littoe bbit moree thban juxt yur articles?I mean, hat youu saay
iis fundamenttal aand everything. Buut thinhk off iif yoou addxed sme greaqt visuuals
orr viceos to give youir posts more, “pop”! Youur contenht
iss excellent butt with images aand video clips, thiss site could undeiably bee one
oof thee bsst inn itts field. Awessome blog!
ofvd9wuaptwuvdudy55y