background

The parent component

<template>
    <div ref="son" :sonName="name"></div>
    <button @click="change"></button>
</template>

<script>
    data() {
        return {
            name: ' ',}},methods: {
        change() {
            this.name = 'father'
            console.log(111)
            this.$refs.son.print()
            this.test()
        },
        test() {
            console.log(222)}},</script>
Copy the code

Child components

<script>
    props: ['sonName'].methods: {
        print() {
            console.log(this.sonName)
            console.log(333)}},watch: {
        sonName(val) {
            console.log(444)}},</script>
Copy the code

When the parent component button is clicked, the result is printed

111
' '
333
222
444
Copy the code

The original plan of the project was to obtain the props value of the child component after changing the data value of the parent component. However, the current result is that after the parent component changes the data value, the watch method of the child component is not triggered immediately. At present, it seems that the watch method of the child component is triggered after executing the method of the parent component


Problem solving:

Modify the parent component’s method logic for calling child components:

<template>
    <div ref="son" :sonName="name"></div>
    <button @click="change"></button>
</template>

<script>
    data() {
        return {
            name: ' ',}},methods: {
        change() {
            this.name = 'father'
            console.log(111)
            // Change it here
            this.$nextTick((a)= >{
                this.$refs.son.print()
            })
            this.test()
        },
        test() {
            console.log(222)}},</script>
Copy the code

Print the result:

111
222
444
'father'
333
Copy the code

Thanks to the comments, I went back to the documentation about nextTick and finally understood the meaning of asynchronous update queue in VUE