vue父子組件相互傳值是非常常見(jiàn)的場(chǎng)景,例如
彈框場(chǎng)景或公共功能模塊的封裝場(chǎng)景。常用的是采用$emit和props的方式。
其中$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