在 vue 3 的组合 API 中尝试从子组件更改父组件的状态时,this.$emit() 不是一个函数
//父组件
<template>
<childComp @onchangeData='changeData' />
</template>
<script>
setup() {
const state = reactive({
data: 'anything
});
function changeData(v){
state.data = v
}
return { changeData}
},
</script>
//Child
<template>
<button @click='change('hello')' />
</template>
<script>
setup() {
function change(v){
this.$emit('onchangeData', v)
}
return{change}
},
</script>
我正在努力通过孩子的按钮单击来改变父母的反应状态。它说 this.$emit 不是一个函数。我尝试了很多方法,例如使用 @onchangeData='changeData()'
而不是 @onchangeData='changeData'
、使用箭头函数等。但没有任何效果。在这里,我编写了一个示例和最少的代码以保持简单。但我希望我的问题是清楚的。
//Parent component
<template>
<childComp @onchangeData='changeData' />
</template>
<script>
setup() {
const state = reactive({
data: 'anything
});
function changeData(v){
state.data = v
}
return { changeData}
},
</script>
//Child
<template>
<button @click='change('hello')' />
</template>
<script>
setup() {
function change(v){
this.$emit('onchangeData', v)
}
return{change}
},
</script>
I am struggling to change the parents' reactive state from the child's button click. It's saying this.$emit is not a function. I tried many ways like using @onchangeData='changeData()'
instead of @onchangeData='changeData'
, using arrow functions etc. But nothing works. Here, I wrote an example and minimal code to keep it simple. But I hope my problem is clear.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看下面的代码片段,
this
的组成与 options API 中的不同,因此您需要使用传递给 setup 函数的emit:Look at following snippet,
this
is not the same in composition as in options API, so you need to use emit passed to setup function: