vue組件通信

1.父組件傳遞數(shù)據(jù)給子組件

思路:在父組件中定義inputValue屬性,然后再props接收參數(shù)
注意此方法是傳遞的動(dòng)態(tài)數(shù)據(jù),在父組件接收時(shí)需要應(yīng)用:(v-bind的簡(jiǎn)寫)接收
代碼如下:

父組件

<template>
  <div>
    <input type="text" v-model="msg">
    <br>
    //將子控件屬性inputValue與父組件msg屬性綁定
    <child :inputValue="msg"></child>
  </div>
</template>
<style>

</style>
<script>
  export default{
    data(){
      return {
        msg: '請(qǐng)輸入'
      }
    },
    components: {
      child: require('./Child.vue')
    }
  }
</script

子組件

<template>
  <div>
    <p>{{inputValue}}</p>
  </div>
</template>
<style>

</style>
<script>
    export default{
        props: {
          inputValue: String
        }
    }
</script>

2.子組件向父組件傳遞
(1)子組件$emit,父組件v-on
思路:子組件使用$emit,$('自定義的事件名稱',需要傳遞的參數(shù)),在父組件中v-on:自定義事件的名稱=“接收到參數(shù)后的方法”

代碼如下:

父組件

<template>
  <div>
//message為子控件上綁定的通知;recieveMessage為父組件監(jiān)聽到后的方法
    <child2 v-on:message="recieveMessage"></child2>
  </div>
</template>
<script>
  import {Toast} from 'mint-ui'
  export default{
    components: {
      child2: require('./Child2.vue'),
      Toast
    },
    methods: {
      recieveMessage: function (text) {
        Toast('監(jiān)聽到子組件變化'+text);
      }
    }
  }
</script>

子組件

<template>
  <div>
    <input type="text" v-model="msg" @change="onInput">
  </div>
</template>
<script>
  export default{
    data(){
      return {
        msg: '請(qǐng)輸入值'
      }
    },
    methods: {
      onInput: function () {
        if (this.msg.trim()) {
          this.$emit('message', this.msg);
        }
      }
    }
  }
</script>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • vue 組件通信分為父組件與子組件通信、子組件與父組件通信、非父子關(guān)系組件通信三種 第一種大家都知道用props,...
    lyn911閱讀 2,285評(píng)論 0 0
  • 這篇筆記主要包含 Vue 2 不同于 Vue 1 或者特有的內(nèi)容,還有我對(duì)于 Vue 1.0 印象不深的內(nèi)容。關(guān)于...
    云之外閱讀 5,180評(píng)論 0 29
  • 組件通信各種情況總結(jié)VUE是以數(shù)據(jù)驅(qū)動(dòng)的MVVM框架,又是模塊化開發(fā),所以各個(gè)組件間的通信傳遞數(shù)據(jù)非常重要,在項(xiàng)目...
    流年_338f閱讀 626評(píng)論 0 2
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,663評(píng)論 19 139
  • 1) 父組件給子組件傳值 利用Vue的組件機(jī)制,父親組件通過 v-bind指令給子組件綁定一個(gè)屬性,屬性值為父組件...
    小楓學(xué)幽默閱讀 587評(píng)論 1 7

友情鏈接更多精彩內(nèi)容