组件代码 <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 1emit step 2emit step 31 而此时的组件中的 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') } }
组件代码
容器代码
点击按钮,依次打印:
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}利用的是参数在函数中传递时,基础类型为具体值,而对象类型为引用,操作的为同一个对象。