英文:
Updating prop value in child component when parent property updates Vue 3
问题
我遇到了更新子组件中属性值的问题,文档上说“当父组件的属性更新时,它会传递到子组件”,但实际情况并非如此。我已经对代码进行了总结:
父组件:
<script setup>
import Child from "../components/Child.vue";
var counter = 0;
setInterval(() => {
counter++;
console.log(counter);
}, 2000);
</script>
<template>
<Child :counter="counter"/>
</template>
子组件:
<script setup>
import { ref, defineProps } from "vue";
const props = defineProps(['counter']);
const count = ref(props.counter);
</script>
<template>
<h1>{{ count }}</h1>
</template>
有人知道可能出了什么问题吗?我已经尝试将一个 ref 对象传递给子组件,并在属性上使用 watch 函数,但没有奏效。
英文:
I'm having troubles to update the value of a prop in a child component, the documentation says "when the parent property updates, it will flow down to the child" but that is not happening, i've made a summary of the code:
Parent's:
<script setup>
import Child from "../components/Child.vue"
var counter = 0
setInterval(() => {
counter++
console.log(counter)
}, 2000)
</script>
<template>
<Child :counter="counter"/>
</template>
Child's:
<script setup>
import { ref } from "vue"
const props = defineProps(['counter'])
const count = ref(props.counter)
</script>
<template>
<h1>{{ count }}</h1>
</template>
Anyone knows what could be wrong? I already tried to pass a ref object to the child and to put a watch function on the prop but it didn't work
答案1
得分: 0
Gaetan C.的回答是正确的,但还不够。
counter数据属性不是响应式的,更改它不会触发更新。
var counter = 0;
应该改为:
const counter = ref(0);
然后:
counter.value++;
这是示例代码。
英文:
The antwort from Gaetan C. is right, but not enough.
The counter data property is not reactive and changing it will not trigger updates.
var counter = 0;
should be
const counter = ref(0);
and then
counter.value++;
Here is the playground
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-js -->
const { createApp, ref } = Vue;
const Child = {
props: ['counter'],
template: '<h1>{{ counter }}</h1>'
}
const App = {
components: {
Child
},
setup() {
const counter = ref(0);
setInterval(() => {
counter.value++
}, 2000)
return { counter }
}
}
const app = createApp(App)
app.mount('#app')
<!-- language: lang-html -->
<div id="app">
<child :counter="counter"></child>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论