vue父子組件之間的通信

一、父組件傳值給子組件

1.子組件,首先定義一個子組件,然後在子組件中註冊props,然後創建一個名爲infos的屬性,用來接收從父組件傳過來的數據

<template>
  <div>
    <div>{{infos}}</div>
  </div>
</template>
<script>
  export default {
    // 接受父組件的值
    props:{
        infos:{
          type:String //傳值的數據類型
        }
      },
  }
</script>
<style>
</style>

2.父組件,在父組件中引入子組件,並加入子組件標籤,在子組件標籤中添加子組件props中創建的屬性,將值通過該屬性傳遞給子組件

<template>
    <div>
        <div>父組件</div>
        <child :infos="parentInfo"></child>  
    </div>
</template>
 
<script>
 
import child from './child'  //引入child組件
export default {
    data() {
            return {
                parentInfo: 'a message from parent'  //在data中定義需要傳入的值
            }
        },
        components: {
            child
        }
}
</script>
<style>
</style>

 

二、子組件傳值給父組件

1.子組件

首先子組件要觸發一個自定義事件;然後將需要傳的值作爲$emit的第二個參數,該值將作爲實參傳給響應自定義事件的方法(下面的例子是傳遞多個數據的處理方法),可按自己的業務邏輯設置傳的值的數據格式與內容。

<template>
  <div>
    <div @click="toParent('信息一','信息二')"></div>
  </div>
</template>
<script>
  export default {
     methods:{
        //此處是傳遞了多個參數,根據自己的業務邏輯處理
	toParent(info1,info2){
            var infos = [info1,info1]
            this.$emit("listenToParent",infos);
        }
      }
  }
</script>
<style>
</style>

2.父組件

在父組件中註冊子組件,並加入子組件標籤,子組件標籤上綁定對自定義事件的監聽,在監聽的方法裏面即可拿到子組件傳過來的值

<template>
    <div>
        <div>父組件</div>
        <child v-on:listenToParent="getChildMsg"></child>  
    </div>
</template>
 
<script>
 
import child from './child'  //引入child組件
export default {
    data() {
            return {
                
            }
        },
        components: {
            child
        },
        methods:{
            getChildMsg:function(msg){
              console.log(msg)
            }
        }
}
</script>
<style>
</style>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章