vue父組件點擊觸發子組件事件的執行個體講解,vue執行個體講解

來源:互聯網
上載者:User

vue父組件點擊觸發子組件事件的執行個體講解,vue執行個體講解

最近在學習Vue父子組件通訊的問題,剛好遇到一個父子之間事件事件派發與接收,在這裡記錄一下,在這裡我使用的是ref

給子組件註冊引用資訊。官網是這樣解釋的

ref 被用來給元素或子組件註冊引用資訊。引用資訊將會註冊在父組件的 $refs 對象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素; 如果用在子組件上,引用就指向組件執行個體:

父組件app.vue

<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>

子組件popup.vue

<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>

我把這個執行個體分為幾個步驟解讀:

1、父組件的button元素繫結click事件,該事件指向notify方法

2、給子組件註冊一個ref="child"

3、父組件的notify的方法在處理時,使用了$refs.child把事件傳遞給子組件的parentMsg方法,同時攜帶著父組件中的參數msg

4、子組件接收到父組件的事件後,調用了parentMsg方法,把接收到的msg放到message數組中

運行結果如下:

以上這篇vue父組件點擊觸發子組件事件的執行個體講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.