隨手寫一下自己的淺顯的理解
一.子組件從父組件獲取數據
1.數據回傳
我們在子組件中prop內聲明需要用到的父組件值的類型,如:
props: {
item: Object,
index: Number
}
這表明我們的子組件代碼中只需要用到一個名為item的對象和一個名為index的數值。
下面是父組件中data內聲明的item數據:
{
userPic: '../../static/demo/userpic/12.jpg',
userName: '昵稱',
isSubscribe: false,
title: '我是標題1',
type: 'img', //img OR video
titlePic: '../../static/demo/datapic/21.jpg',
infoNum: {
flag: 0, //0->用戶還沒有操作;1->用戶已經👍過;2->用戶已👎過
likeNum: 10,
dislikeNum: 10
},
//用對象因為每位用戶只能👍或👎一次
commentNum: 10,
shareNum: 10
}
這樣我們在寫子組件時就可以使用父組件中這個item的內容,如:
<view class="index-list2" @tap="openDetail">{{ item.title }}</view>
<view class="index-list3" @tap="openDetail">
<image :src="item.titlePic" mode="widthFix" lazy-load></image>
<!-- widthFix寬度不變高度自變化,比例不變 -->
<template v-if="item.type === 'video'">
<view class="index-list-play icon iconfont icon-bofang"></view>
<view class="index-list-playInfo ">
<text>{{ item.playNum }}次播放 {{ item.videoTime }}</text>
</view>
</template>
</view>
這里就使用了父組件數據內的很多內容如title,playNum等等屬性。
當然子組件只是父組件的組成部分,父組件引用子組件:
<index-list :item="item" :index="index1"></index-list>
這里:item,:index正是我們在子組件props中聲明的部分,里面的內容填入父組件的數據。
當然,引用子組件之前還得import導入還有在components標簽中注冊,缺一不可:
import indexList from "../../components/index/index-list.vue";
components: {
indexList
//這里一定要對引入的組件進行注冊
}
2.方法回傳
子組件中寫了一個點擊方法
<view class="swiper-tab-list" @tap="taptap(index)"/>
要將參數變化傳給父組件,則在taptap該方法中寫:
taptap(index) {
this.$emit('tapFun', index);
/* 觸發當前實例上的事件。附加參數都會傳給監聽器回調 tabfun為自定義方法名,index為要傳遞的參數*/
}
那么我們在父調用該子組件時:
<swiper-tab-head :tabBars="tabBars" :tabIndex="tabIndex" @tapFun="tapFun">
</swiper-tab-head>
@tapFun為子組件中自定義的方法名,其中就帶有參數index,接着在自定義方法tapFun中就可以使用該參數,如下:
tapFun(index) {
// console.log(index);
this.tabIndex = index;
}
二.父組件從子組件獲取數據
我們在父子間中對引用的子組件寫上注冊ref信息,ref的值是可以自定義的
ref
被用來給元素或子組件注冊引用信息。引用信息將會注冊在父組件的$refs
對象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子組件上,引用就指向組件實例。
<uni-popup ref="showPOP"> </uni-popup>
接着就可以在方法中通過this.$refs.showPOP如此拿到子組件中的數據,可以進行取值或更改
close() {
// 使用$refs對子組件data進行內容更改
this.$refs.showPOP.showPopup = false;
}