vue typescrip 子组件传值给父组件怎么写

vue typescrip 子组件传值给父组件怎么写。
使用 @emit 触发不了啊

阅读 4k
1 个回答

组件代码

<template>
    <button type="button" @click="componentHandleClick(emitValue)">测试emit</button>
</template>
<script lang="ts">
export default class HelloWorld{
    emitValue: any = 1
    @Emit('onHelloClick')
    componentHandleClick(val: any) {
        console.log('emit step 1')
        this.emitValue += 1
        console.log('emit step 2')
    }
}
</script>

容器代码

<template>
      <hello-world @onHelloClick="handleHelloClick($event)"></hello-world>
</template>
<script lang="ts">
export default class App{
    
    handleHelloClick(val){
        console.log('emit step 3')
        console.log(val); // 打印1
    }
}
</script>

点击按钮,依次打印:
emit step 1
emit step 2
emit step 3
1

而此时的组件中的 emitValue 已经为 2,而传出去的值却是 1

如要使得 emitValue 为组件改变之后的值,可以把 emitValue 转变成对象: emitValue = {val:1}
组件绑定函数改为 emitValue.val+=1,执行完毕,emitValue{val:2}

然后 handleHelloClick 接收到的参数则为 `{val:2}

利用的是参数在函数中传递时,基础类型为具体值,而对象类型为引用,操作的为同一个对象。

<template>
    <button type="button" @click="componentHandleClick(emitValue)">测试emit</button>
</template>
<script lang="ts">
export default class HelloWorld{
    emitValue = {value:1} // here
    @Emit('onHelloClick')
    componentHandleClick(val: any) {
        console.log('emit step 1')
        this.emitValue.value += 1 // here
        console.log('emit step 2')
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题