在vue 3中观察父组件的子属性

wit*_*ein 6 vue.js vue-component vuejs3 vue-composition-api vue-script-setup

我想知道如何使用组合 API 观察 Vue 3 中父组件的子属性(我正在使用实验脚本设置)。

<template>//Child.vue
  <button 
    @click="count++" 
    v-text="'count: ' + count" 
  />
</template>

<script setup>
import { ref } from 'vue'

let count = ref(1)
</script>
Run Code Online (Sandbox Code Playgroud)
<template>//Parent.vue
  <p>parent: {{ count }}</p> //update me with a watcher
  <Child ref="childComponent" />
</template>


<script setup>
import Child from './Child.vue'
import { onMounted, ref, watch } from 'vue'

const childComponent = ref(null)
let count = ref(0)

onMounted(() => {
  watch(childComponent.count.value, (newVal, oldVal) => {
    console.log(newVal, oldVal);
    count.value = newVal
  })
}) 
</script>
Run Code Online (Sandbox Code Playgroud)

我想了解如何从父组件观察子组件的变化。我的无效解决方案受到此处询问的 Vue.js 2 解决方案的启发。所以我不想发出,count.value只是观察变化。

谢谢你!

小智 3

正如您可以在此处看到的,其中的绑定<script setup>是“默认关闭”的。

但是您可以明确公开某些参考文献。为此,您使用useContext().expose({ ref1,ref2,ref3 })

因此只需将其添加到 Child.vue 中:

import { useContext } from 'vue'

useContext().expose({ count })
Run Code Online (Sandbox Code Playgroud)

然后将Parent.vue中的Watcher更改为:

watch(() => childComponent.value.count, (newVal, oldVal) => {
    console.log(newVal, oldVal);
    count.value = newVal
  })
Run Code Online (Sandbox Code Playgroud)

它有效!