開發與維運

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來實現傳遞了。

Leave a Reply

Your email address will not be published. Required fields are marked *