vue中methods的方法执行与watch触发顺序探究,nextTick异步更新队列的影响

3,017

背景

父组件

<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>

子组件

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

当点击父组件button后,打印结果为

111
''
333
222
444

项目原本计划是,在改变父组件data值后,再获取子组件中props的值等后续操作,但目前的结果是,在父组件改变data中值后,并没有立刻触发子组件的watch方法,目前感觉像是执行完父组件的方法后,再去触发子组件的watch


问题解决:

修改父组件中的调用子组件的方法逻辑:

<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.$nextTick(()=>{
                this.$refs.son.print()
            })
            this.test()
        },
        test() {
            console.log(222)
        },
    },
</script>

此时打印结果:

111
222
444
'father'
333

感谢评论中大佬的解析,又回去翻了文档中关于nextTick的一些说明,通过实例终于理解了vue中异步更新的含义 官方“异步更新队列”说明