小程序父子组件传值,调用方法,observer监听组件数据变化(image组件封装)
一、父组件给子组件传值(image组件封装)
父组件传值
// index.wxml
<imgModule src="{
{imgSrc}}"></imgModule>
// index.js
Page({
data: {
imgSrc: "http://...jpg"
},
})
// index.json
{
"usingComponents": {
"imgModule":"/components/global/image/index"
}
}
子组件接收
// components/global/image/index.wxml
<image src="{
{imgSrc}}" />
// components/global/image/index.js
Component({
/**
* 组件的属性列表
*/
properties: {
src: {
type: String,
value: "",
// observer数据监听,监听src变化获取图片临时路径
observer(nv, ov, path) {
if (nv) {
// 显示图片
wx.downloadFile({
header: {
'cookie': wx.getStorageSync("Set-Cookie")
},
url: nv,
success: (res) => {
this.setData({
imgSrc: res.tempFilePath
})
}
})
}
}
}
},
})
二、子组件调用父组件函数,给父组件传值
// 子组件
this.triggerEvent("gotoDetail", {
id:"id"})
// 父组件
<newsList id="newsList" bindgotoDetail="handleGotoNewsDetail"></newsList>
三、父组件调用子组件的值、函数
// 父组件
<newsList id="newsList" listArr="{
{culturalList}}" bindgotoDetail="handleGotoNewsDetail"></newsList>
// 父组件直接获取子组件的数据
this.selectComponent('#newsList')
this.selectComponent('#newsList').gotoDetailById() // 父组件调子组件的函数
this.selectComponent('#newsList').data.listArr // 父组件调子组件的值