前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vue中在父组件点击按钮触发子组件的事件

vue中在父组件点击按钮触发子组件的事件

作者头像
江咏之
发布2022-06-16 09:29:03
5.8K0
发布2022-06-16 09:29:03
举报
文章被收录于专栏:技术社区

我把这个实例分为几个步骤解读:

1、父组件的button元素绑定click事件,该事件指向notify方法 2、给子组件注册一个ref=“child” 3、父组件的notify的方法在处理时,使用了$refs.child把事件传递给子组件的parentMsg方法,同时携带着父组件中的参数msg 4、子组件接收到父组件的事件后,调用了parentMsg方法,把接收到的msg放到message数组中

父组件

代码语言:javascript
复制
<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>

子组件

代码语言:javascript
复制
<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>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-10-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档