vue父子組件通過(guò)$emit和props實(shí)現(xiàn)相互傳值

vue父子組件相互傳值是非常常見(jiàn)的場(chǎng)景,例如彈框場(chǎng)景公共功能模塊的封裝場(chǎng)景。常用的是采用$emitprops的方式。
其中$emit是子組件向父組件傳值,props是父組件向子組件傳值。
以下為全部代碼

父組件FirstPage.vue

<template>
  <div>
    <!-- 父組件取出子組件傳遞過(guò)來(lái)的json數(shù)據(jù),并顯示到父組件的頁(yè)面上 -->
    <div class='parentClass'>我是父組件:子傳父為{{toParent}}</div>
    <!-- 父組件通過(guò)自定義的toChild1和toChild1屬性,向子組件傳值 -->
    <!-- toChild1是靜態(tài)屬性,對(duì)應(yīng)的值為Apple -->
    <!-- :toChild2是動(dòng)態(tài)屬性,對(duì)應(yīng)的值不是attributeValue,而是orange -->
    <!-- 父組件通過(guò)@toParent來(lái)監(jiān)聽(tīng)子組件傳遞過(guò)來(lái)的事件,然后通過(guò)自定義的toParentValue函數(shù)來(lái)觸發(fā) -->
    <PassChild toChild1='Apple' :toChild2='attributeValue'  @toParent='toParentValue'></PassChild>
  </div>
</template>
<script>
import PassChild from "../components/PassChild.vue";

export default {
  data() {
    return {
      // 默認(rèn)值
      toParent:'',
      // 動(dòng)態(tài)屬性值
      attributeValue:'orange'
    };
  },
  methods: {
    toParentValue(value){
      // 父組件取出子組件傳遞過(guò)來(lái)的json數(shù)據(jù),并顯示到父組件的頁(yè)面上
      this.toParent = value.name;
    }
  },
  components: {
    PassChild:PassChild,
  }
};
</script>
<style>
.parentClass{
  margin:0 auto;
  width:600px;
  height:100px;
  text-align:center;
  color:orange;
  font-size:30px;
}
</style>

子組件PassChild.vue

<template>
  <div class='childContainer'>
        我是子組件:父?jìng)髯訛閧{toChild1}},{{toChild2}}
  </div>
</template>
<script>
export default {
  // 父組件向子組件傳值,通過(guò)props接收
  props: {
      toChild1: {
        type: String,
        required: true, // 父組件必須給子組件傳遞toChild1屬性,否則會(huì)報(bào)錯(cuò)
        default: "toChild1的默認(rèn)值"http:// 如果父組件沒(méi)有給子組件傳遞toChild1屬性,那么以默認(rèn)值代替
      },
      toChild2: {
        type: String,
        default: "toChild2的默認(rèn)值"http:// 如果父組件沒(méi)有給子組件傳遞toChild2屬性,那么以默認(rèn)值代替
      }
 },
  data() {
    return {};
  },
  methods: {},
  mounted(){
       // 子組件向父組件傳值(通過(guò)自定義toParent事件,并攜帶參數(shù)),值為json數(shù)據(jù){"name":'CoderZB','sex':'man'}。當(dāng)然也可以傳遞單個(gè)字符串
       this.$emit("toParent",{"name":'CoderZB','sex':'man'});
  }
};
</script>
<style>
.childContainer{
    width: 300px;
    height: 100px;
    line-height: 100px;
    text-align: center;
    margin: 0 auto;
    background-color: red;
}
</style>

效果截圖

image.png
最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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