天天看點

Vue 的父子通信【props、$emit】

vue中父子通信是常用到的技術點,有多種方法可以進行傳值,複雜的傳值方式去參考 vueX

。今天我們簡單說下常用的2種方式:

父傳子:props傳值

子傳父:$emit

1. ----------父傳子----------

父元件給子元件傳值,需要在子元件中添加props進行接收父元件傳來的值。

父元件:

随便封裝一個子元件,起名叫

childComponent

。給引入的子元件中傳一個“我是父元件”,随便定義一個hello接收。

<!-- 父元件-->

<template>
  <div class="aaa">
  
    <childComponent hello="我是父元件"></childComponent>
    
  </div>
</template>
<script>
// 引入子元件
import childComponent from "/components/childComponent.vue";
export default {
  data() {
    return {};
  },
  components: {
    // 要在components中注冊子元件才能使用
    childComponent
  },
  methods: {}
};
</script>
<style scoped></style>

           

子元件:

div中的hello會顯示“我是父元件”,這是從父元件通過props傳過來的

<!-- 子元件-->
<template>
  <div class="aaa">
    
    <div>{{ hello }}</div>
    
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 因為props中接收了hello屬性,是以data中不能再定義相同的hello屬性。
    };
  },
  // props 中接收在父元件中定義的hello
  props: {
    hello: {
      type: String // 在hello中加入了type:String,是告訴其他人,hello隻接收字元串内容,傳其他的會報錯。這樣對于團隊合作更嚴謹。當然可以什麼都不加,直接寫hello。
    }
  }
};
</script>
<style scoped></style>
           

這樣子元件在頁面上就會顯示“我是父元件”這句話了,當然,這個值可以動态綁定,傳遞你想要傳遞的值,也可以傳遞布爾值,數組等資訊。

2.----------子傳父 $emit----------

this.$emit(‘要觸發的方法’,參數)

我們随便定義一個要觸發的方法,叫

aaa

,然後傳一個 123 的參數給父元件

<!-- 子元件-->
<template>
  <div class="aaa">
    <button @click="handleClick">子元件</button>
  </div>
</template>
<script>
export default {
  data() {
    return {};
  },
  methods: {
    // 點選按鈕上邊button按鈕,調用這個handleClick方法,通過$emit觸發aaa,把 123 傳過去。父元件通過 aaa 接收這個值。(往下看父元件中的内容)。
    handleClick() {
      this.$emit("aaa", 123);
    }
  }
};
</script>
<style scoped></style>
           

父元件中引入的子元件裡,放入剛才通過$emit觸發的方法 aaa,然後随便定義一個方法

getChildData

,它的值就是傳遞過來的123

<!-- 父元件-->

<template>
  <div class="aaa">
    <childComponent @aaa="getChildData"></childComponent>
  </div>
</template>
<script>
// 引入子元件
import childComponent from "/components/childComponent.vue";
export default {
  data() {
    return {};
  },
  components: {
    // 要在components中注冊子元件才能使用
    childComponent
  },
  methods: {
    // aaa 接收到的屬性,随便定義一個函數 getChildData 方法來接收
    getChildData(data) {
      console.log(data); // 這個data就是子元件傳遞過來的值 123
    }
  }
};
</script>
<style scoped></style>
           

仔細看代碼,相信你會了解的父子通信的。那麼兄弟元件之間也可以通信,是通過子傳父,在父傳子,這樣就實作了子和子傳遞了,也就是兄弟通信,父元件作為中間的橋梁。除了這種方法,還可以用中央事件總線(bus)來進行傳遞,不過現在很少會用到bus來實作傳遞了。

繼續閱讀