Vue3 学习笔记草稿
# vue3 defineExpose 时序问题
有这么一个场景,父组件修改传递给子组件的 prop 并调用子组件的方法,而在该子组件方法中会读取 props。请问子组件方法中读取的 props 是修改前还是修改后的值?
<script setup lang="ts">
import { ref, nextTick } from 'vue'
import Comp from './Comp.vue';
const count = ref(0)
const comRef = ref();
const update = () => {
count.value++
comRef.value.say()
}
</script>
<template>
<div @click="update">ttt {{ count }}</div>
<Comp :count="count" ref="comRef"></Comp>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
结论:读取的是修改前的值,如果想要确保子组件执行时读取的是新的 prop 值,需要用 nextTick 包装一下
const update = () => {
count.value++
nextTick(() => {
comRef.value.say()
})
}
1
2
3
4
5
6
2
3
4
5
6
编辑 (opens new window)
上次更新: 2024/09/09, 12:33:00