Vue官网
仅仅是个人学习的记录
子组件可以使用$emit调用父组件中的方法并传递数据
- 子组件中定义响应事件: 比如这里的sendMsgToParent('hello world'),这里带了参数'hello world'
- 子组件中sendMsgToParent方法通过$emit发射了一个名为fromChildMsg的事件
- 父组件实现子组件中$emit定义的fromChildMsg方法,且触发了一个新的方法,这里为showChildMsg
- 父组件实现showChildMsg
子组件:
<template>
<div class="child">
<van-button
type="primary"
@click="sendMsgToParent('hello world')">点击将'hello world'发射给父组件
</van-button>
</div>
</template>
<script>
export default {
name: "ChildModule",
methods: {
sendMsgToParent(value) {
this.$emit('fromChildMsg', value);
},
}
}
</script>
<style scoped lang="less">
.child {
display: flex;
justify-content: center;
margin: 16px;
padding: 16px;
}
</style>
父组件:
<template>
<div>
<child-module @fromChildMsg="showChildMsg"></child-module>
</div>
</template>
<script>
import ChildModule from "../../components/child-module";
export default {
name: "CurtisTest",
components: {
ChildModule
},
data() {
return {
}
},
methods: {
showChildMsg(data) {
this.$toast({message: data})
console.log('>>>show child msg:', data)
},
}
}
</script>
<style scoped>
</style>
image.png
网友评论