我想知道如何使用组合 api 观察 Vue 3 中父组件的子属性(我正在使用实验脚本设置 https://github.com/vuejs/rfcs/blob/script-setup-2/active-rfcs/0000-script-setup.md).
<template>//Child.vue
<button
@click="count++"
v-text="'count: ' + count"
/>
</template>
<script setup>
import { ref } from 'vue'
let count = ref(1)
</script>
<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>
我想了解如何从父组件观察子组件的变化。我的不起作用的解决方案的灵感来自Vue.js 2 解决方案在这里询问 https://stackoverflow.com/questions/51225378/how-to-watch-child-properties-changes-from-parent-component。所以我不想发出count.value
但只要注意变化即可。
谢谢你!
里面的绑定<script setup>
如您所见,“默认关闭”here https://github.com/vuejs/rfcs/blob/script-setup-2/active-rfcs/0000-script-setup.md#closed-by-default.
但是您可以明确公开某些参考文献。
为此,您使用useContext().expose({ ref1,ref2,ref3 })
因此只需将其添加到 Child.vue 中:
import { useContext } from 'vue'
useContext().expose({ count })
然后将Parent.vue中的Watcher更改为:
watch(() => childComponent.value.count, (newVal, oldVal) => {
console.log(newVal, oldVal);
count.value = newVal
})
它有效!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)