Project scenario:
In the cyclic data list of the parent component, there is an event in the list to click to open a child component;
The value of the child component to be updated in the parent component
Problem Description
In the cyclic data list of the parent component, click to open a subcomponent. After the A data opens the subcomponent, the B data opens the subcomponent again. At this time, the A data will be cached in the subcomponent.
Cause Analysis:
The subcomponent is not refreshed, or stays in the previous data cache
solution:
Add key value to component
Principle: After the key value changes, the component will be automatically re-rendered
The role of the key in Vue is mainly to update the dom efficiently. It can also be used to force the element/component to be replaced instead of reusing it. The completion triggers the life cycle hook of the component and triggers the transition.
<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>