About notifying the child component to re-render after the parent component asynchronously updates data

    • use key

In Vue projects, in many cases public components are extracted to reduce the amount of code, improve development efficiency, and facilitate maintenance. In many cases, child components are referenced in parent components. Render child components that can have different data by adding attributes to the child component tags referenced in the parent component. But there is a characteristic of Vue components. If the property value we passed this time is the same as the last time, the function called in watch will not be executed because there are no new changes in the properties monitored by watch (the value this time is the same as the last value). ), causing the corresponding data to remain unchanged. The created() life cycle function is also executed only once.

But sometimes we need this component to regenerate the dom element every time and execute the created() function every time. At this time, the key attribute in vue is used.

The key attribute is basically the same as the key attribute of react (personal understanding, please correct me if there are any errors).

The key attribute is not used by developers, but is used when rendering vue elements. This key value will be compared every time it is rendered. If the key value this time is different from the previous key value, The dom element will be re-rendered only if it is the same, otherwise the last element state will be retained.

According to this principle, we can directly bind a timestamp to the key.

parent component

<template>

<div>

<div>

<h1>Parent</h1>

<button @click="handleLoad">Click to reload child</button>

</div>

<children :key="timer"></children>

</div>

</template>

<script>

import children from '@/components/parent/children'

export default {

name: 'parent',

components: { children },

data () {

return {

timer: ''

}

},

methods: {

handleLoad () {

this.timer = new Date().getTime()

}

}

}

</script>

Subassembly

<template>

<div>

child

</div>

</template>

<script>

export default {

name: 'children',

data () {

return {}

},

created () {

console.log('Reloaded')

}

}

</script>

————————————————

Copyright statement: This article is an original article by CSDN blogger "zhaoyizhu1990" and follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this statement when reprinting.

Original link: https://blog.csdn.net/zhaoyizhu1990/article/details/105482158

2. Use v-if to determine whether to get the asynchronously loaded data, and then decide whether to render the subcomponent;

3. Subcomponents use watch to monitor

Guess you like

Origin blog.csdn.net/weixin_43883849/article/details/128813109