I’m wondering how I can observe child properties from the parent component in Vue 3 using the composition api (I’m working with the experimental script setup).
JavaScript
x
13
13
1
<template>//Child.vue
2
<button
3
@click="count++"
4
v-text="'count: ' + count"
5
/>
6
</template>
7
8
<script setup>
9
import { ref } from 'vue'
10
11
let count = ref(1)
12
</script>
13
JavaScript
1
21
21
1
<template>//Parent.vue
2
<p>parent: {{ count }}</p> //update me with a watcher
3
<Child ref="childComponent" />
4
</template>
5
6
7
<script setup>
8
import Child from './Child.vue'
9
import { onMounted, ref, watch } from 'vue'
10
11
const childComponent = ref(null)
12
let count = ref(0)
13
14
onMounted(() => {
15
watch(childComponent.count.value, (newVal, oldVal) => {
16
console.log(newVal, oldVal);
17
count.value = newVal
18
})
19
})
20
</script>
21
I want to understand how I can watch changes in the child component from the parent component. My not working solution is inspired by the Vue.js 2 Solution asked here. So I don’t want to emit the count.value
but just watch for changes.
Thank you!
Advertisement
Answer
The Bindings inside of <script setup>
are “closed by default” as you can see here.
However you can explicitly expose certain refs.
For that you use useContext().expose({ ref1,ref2,ref3 })
So simply add this to Child.vue:
JavaScript
1
4
1
import { useContext } from 'vue'
2
3
useContext().expose({ count })
4
and then change the Watcher in Parent.vue to:
JavaScript
1
5
1
watch(() => childComponent.value.count, (newVal, oldVal) => {
2
console.log(newVal, oldVal);
3
count.value = newVal
4
})
5
And it works!