前端代碼進行抽象與封裝離不開父子組件傳值問題,做的過程中總有梳理不清楚的時候,在此總結一波,一方面是自己梳理梳理思路,另外一方面有需要的夥伴們也可以瞅一瞅,本文是從開始到最後實現數據的一個操作過程;
父組件向子組件傳值
1、可抽離的靜態頁面
首先是看一下自己的靜態頁面有哪些相似之處可以被抽象出來,如下面這個頁面,看似不一樣,實則都是一樣的,只是圖標和文字內容不一致,OK瞭解後我們可以開始設計靜態頁面啦;
<div class="settingListSwitch">
<img class="settingLogoSwitch" src="../../public/settings/顯示.png"/>
<span class="words">顯示單詞</span>
<van-switch size="24px" class="switchSwitch" />
</div>
2、父組件操作
//引入子組件
import momoTemplate from "../../components/momoTemplate.vue";
//註冊子組件
export default{
components:{ momoTemplate }
}
//引入常量js-傳入數據
import { settingData, settingSwitchData } from "../../Entity/settingDataEntity";
所引入JS:import { settingData, settingSwitchData } from “…/…/Entity/settingDataEntity”;其中的“settingData”“settingSwitchData”,是我們Js中傳出來的變量
3、顯示數據
- 在props中寫子組件需要的屬性
export default {
props:{
// 顯示文本
allColumnsTitle:{default: "延遲跳轉"},
//顯示開關
allColumnsSwitch:{default:"0"},
//開關狀態
isTrue:{default:"false"},
//顯示圖標
arrowIcon: { default: require("../../public/settings/右.png") },
},
與js數據中的值相對應
2. 父組件-動態綁定數據(子組件需要的數據)
<template>
<momoTemplate
v-for="(item,index) of settingSwitchData"
:key="index"
:settingLogoSwitch="settingSwitchData[0].arrowIcon"
:allColumnsTitle="settingSwitchData[0].allColumnsTitle"
:isTrue="settingSwitchData[0].isTrue"
>
</momoTemplate>
</template>
- 子組件-顯示父組件傳過來的數據
<div class="settingListSwitch">
<img class="settingLogoSwitch" :src="settingLogoSwitch"/>
<span class="words">{{allColumnsTitle}}</span>
<van-switch v-model="isTrue" size="24px" class="switchSwitch" />
</div>
到此父組件向子組件傳值的過程已經完成,接下來是子組件向父組件傳值;
子組件向父組件傳值
1、子組件:
<di>
<van-switch
v-model="isTrue"
@change="selectSwitch"
/>
</div>
// 子組件向父組件傳值
selectSwitch(){
this.childIsTrue=this.isTrue;
this.$emit("listenToChild",this.childIsTrue);
}
2、父組件:
// 接收子組件傳值,綁定
@listenToChild="changeValue"
changeValue(){
},
注意:changeValue()默認參數爲子組件傳遞過來的參數,當我們再傳遞參數時就會覆蓋子組件傳遞過來的參數
父子組件傳值的梳理到此告一段落,個人學習及使用的總結,哪裏理解偏差的,一起交流學習;