vue项目中如何实现在父组件点击按钮触发子组件

发布时间:2020-11-16 15:02:48 作者:Leah
来源:亿速云 阅读:501

今天就跟大家聊聊有关vue项目中如何实现在父组件点击按钮触发子组件,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

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

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>

看完上述内容,你们对vue项目中如何实现在父组件点击按钮触发子组件有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. VUE父组件向子组件传递数据
  2. Vue父组件如何获取子组件中的变量

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue 父组件 子组件

上一篇:jsx语法如何在Vue 3.0中使用

下一篇:Vue 如何实现带参数进入详情页

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》