欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

在vue中如何实现父组件点击触发子组件事件

程序员文章站 2022-05-12 17:26:04
...
下面我就为大家分享一篇vue父组件点击触发子组件事件的实例讲解,具有很好的参考价值,希望对大家有所帮助。

最近在学习Vue父子组件通信的问题,刚好遇到一个父子之间事件事件派发与接收,在这里记录一下,在这里我使用的是ref

给子组件注册引用信息。官网是这样解释的

ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs 对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素; 如果用在子组件上,引用就指向组件实例:

父组件app.vue

<template>
  <p id="app">
  <!--父组件-->
  <input v-model="msg">
  <button v-on:click="notify">广播事件</button>
  <!--子组件-->
  <popup ref="child" ></popup>
  </p>
 </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>

子组件popup.vue

<template>
   <p>
   <ul>
    <li v-for="item in messages">父组件输入了:{{item}}</li>
   </ul>
   </p>
  </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>

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

1、父组件的button元素绑定click事件,该事件指向notify方法

2、给子组件注册一个ref="child"

3、父组件的notify的方法在处理时,使用了$refs.child把事件传递给子组件的parentMsg方法,同时携带着父组件中的参数msg

4、子组件接收到父组件的事件后,调用了parentMsg方法,把接收到的msg放到message数组中

运行结果如下:

在vue中如何实现父组件点击触发子组件事件

在vue中如何实现父组件点击触发子组件事件

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在Vue2.0中实现用户权限控制

详解如何实现vuex(详细教程)

通过vue.js实现微信支付

以上就是在vue中如何实现父组件点击触发子组件事件的详细内容,更多请关注其它相关文章!