问题代码
// parentComponent.vue
<template>
<Child :data="store.count"/>
</template>
<script setup>
import { onMounted } from 'vue'
import { useCount } from '@/stores/count'
import Child from './Child.vue'
// store 获取
const store = useCount()
onMounted(() => {
// 设置数据
store.setNumber('xxxxx')
})
</script>
<template>
<div>{{props.data}}</div>
</template>
<script setup>
const props = defineProps({
data: Array
})
// 数据打印
console.log(props.data, '<<<<<<data')
</script>
问题原因
- 执行顺序问题
onMounted(() => {
// 设置数据
store.setNumber('xxxxx')
})
父组件的数据是在挂载阶段设置的,而子组件的数据是在Create阶段创建的,这就导致了传递的数据看似有数据但是没数据。
执行顺序
// 父组件
<template>
<ChildComponent :data="data"></ChildComponent>
</template>
<script setup>
import { onMounted, onUpdated, ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
const data = ref()
console.log(data.value, '<<<<<<<parent-create')
onBeforeMount(() => {
console.log(data.value, '<<<<<<<parent-before-mount')
})
onMounted(() => {
data.value = 'hello world'
console.log(data.value, '<<<<<<<parent-mounted')
})
onUpdated(() => {
console.log(data.value, '<<<<<<<parent-updated')
})
</script>
// 子组件
<template>
<div>props.data ===> {{ props.data }}</div>
</template>
<script setup>
import { onMounted, onUpdated } from 'vue'
const props = defineProps({
data: String
})
console.log(props.data, '<<<<<<child--create')
onBeforeMount(() => {
console.log(props.data, '<<<<<<child--beforeMount')
})
onMounted(() => {
console.log(props.data, '<<<<<<child--mounted')
})
onUpdated(() => {
console.log(props.data, '<<<<<<child--updated')
})
</script>
输出
可以看到, 执行顺序
父组件[create] -> 父组件[BeforeMount] -> 子组件[create] -> 子组件[BeforeMount] ->
子组件[mount] -> 父组件[mount] -> 子组件[update]
这就是我上面代码会出现问题的原因