我把这个实例分为几个步骤解读:
1、父组件的button元素绑定click事件,该事件指向notify
方法
2、给子组件注册一个ref=“child”
3、父组件的notify
的方法在处理时,使用了$refs.child
把事件传递给子组件的parentMsg
方法,同时携带着父组件中的参数msg
4、子组件接收到父组件的事件后,调用了parentMsg
方法,把接收到的msg
放到message
数组中
父组件
<template>
<div id="app">
<!--父组件-->
<input v-model="msg" />
<button v-on:click="notify">广播事件</button>
<!--子组件-->
<popup ref="child"></popup>
</div>
</template>
<script>
import popup from "@/components/popup";
export default {
name: "app",
data: function () {
return {
msg: "",
};
},
components: {
popup,
},
methods: {
notify: function () {
if (this.msg.trim()) {
this.$refs.child.parentMsg(this.msg);
}
},
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
子组件
<template>
<div>
<ul>
<li v-for="item in messages">父组件输入了:{{ item }}</li>
</ul>
</div>
</template>
<style>
body {
background-color: #ffffff;
}
</style>
<script>
export default {
name: "popup",
data: function () {
return {
messages: [],
};
},
methods: {
parentMsg: function (msg) {
this.messages.push(msg);
},
},
};
</script>
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有