起步 - 從場景中看父子組件間通信


組件間通信是組件開發的,我們既希望組件的獨立性,數據能互不干擾,又不可避免組件間會有聯系和交互。

在vue中,父子組件的關系可以總結為props down,events up

在vue2.0中廢棄了$dispatch$broadcast,子組件使用event發出自定義事件

 父子組件之間的通信

 思考場景如下:

  一個總群(父組件)中大家做自我介紹,

  陌陌、小小、可可、天天 收到 總群發來的消息之后(父傳子將自己的信息發送到總群(子傳父

父組件 

template


<
template> <div> <h4>父組件>></h4> <div> <span>{{ somebody }}</span> 說: 我來自 <span>{{ city }} </span> </div> <hr> <!-- aGirls和noticeGirl通過props傳遞給子組件 --> <!-- introduce通過$emit子組件傳遞給父組件 --> <v-girl-group :girls="aGirls" :noticeGirl="noticeGirl" @introduce="introduceSelf"></v-girl-group> </div> </template>

 我使用的組件間通信:

  • aGirls和noticeGirl通過 props 傳遞給子組件
  • 通過 $emit 子組件傳遞給父組件,v-on來監聽父組件自定義事件($emit的變化)

script

<script>
import vGirlGroup from './components/HelloWorld'
export default {
    name: 'girl',
    components: {
        vGirlGroup
    },
    data () {
        return {
            aGirls:[{
                name:'陌陌',
                city:'GuangZhou'
            },{
                name:'小小',
                city:'BeiJing'
            },{
                name:'可可',
                city:'American'
            },{
                name:'天天',
                city:'HangZhou'
            }],
            somebody:'',
            city:'',
            noticeGirl:''
        }
    },
    methods: {
        introduceSelf (opt) {
            this.somebody = opt.name;
            this.city = opt.city;

            // 通知girl收到消息
            this.noticeGirl = opt.name + ',已收到消息';
        }
    }
}
</script>

這里的 introduceSelf 就是父組件接收到子組件發出的$emit事件處理程序

子組件

 template

<template>
    <div>
      <h4>子組件>></h4>
       <ul>
           <li v-for="(value, index) in girls">
                {{ index }} - {{ value.name }} - {{ value.city }} 
                <button @click="noticeGroup(value.name,value.city)">發送消息</button>
            </li> 
       </ul>
       <div class="msg">接收來自父組件的消息:{{ noticeGirl }}</div>
    </div>
</template>

script

子組件通過$emit發出自定義事件

<script>
export default {
    name: 'girl-group',
    props: {
        girls: {
            type: Array,
            required: true
        },
        noticeGirl: {
            type: String,
            required: false
        }
    },
    methods: {
        noticeGroup (name, age) {
            this.$emit('introduce',{
                name: name,
                age: age
            })
        }
    }
}
</script>

結果

 

到這里,我們已經根據vue2.0父子間通信實現了上面提出的一個場景 .

相比vue1.0的變化:具體可以參考:https://cn.vuejs.org/v2/guide/migration.html#dispatch-和-broadcast-替換

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM