父子組件傳值
靜態傳值
靜態傳值為父組件向子組件傳遞常量數據,因此只能傳遞String字符串類型。
父組件 (parent.wpy)
<view>
<child name="leinov"></child>
</view>
子組件(child.wpy)
<template lang="wxml">
<view>
{{name}}
</view>
</template>
<script>
props={
name:String
}
onLoad(){
console.log(this.name);//leinov
}
</script>
動態傳值
- sync修飾符來達到父組件數據綁定至子組件的效果
- 也可以通過設置子組件props的twoWay: true來達到子組件數據綁定至父組件的效果
- 如果既使用.sync修飾符,同時子組件props中添加的twoWay: true時,就可以實現數據的雙向綁定了。
異步數據父子組件傳值注意
parent
<script>
export default class Parents extends wepy.page {
data = {
tabdata:{}, //下面要用這里必須要寫上
}
async onLoad() {
let data = await getData(,"public/data",{session_key:"1234456"});
this.tabdata= data.tab;
this.$apply();//必須
}
}
</script>
<template lang="wxml">
<view class="title" slot="title"></view>
<view class="title" slot="content">
<Tab :tab.sync="tabdata" ></Tab>
</view>
</template>
child
<template lang="wxml">
<view class="title" slot="title">{{tab}}</view>
</template>
export default class Tab extends wepy.component {
props = {
tab:{
type:Object,
default:null,
twoWay:true
}
}
以下必須注意
- 模版中要給子組件傳的值 在data里要聲明好
- 取到異步值后要使用this.$apply()手動更新組件
- 在父組件中調用子組件的屬性名要加.sync
- 子組件要使用父組件的props必須在props里聲明