The parent-child components of the applet pass values, call methods, and the observer monitors component data changes (image component encapsulation)


1. The parent component passes the value to the child component (image component encapsulation)

pass value from parent component

// index.wxml
<imgModule src="{
    
    {imgSrc}}"></imgModule>
// index.js
Page({
    
    
  data: {
    
    
    imgSrc: "http://...jpg"
  },
})
// index.json
{
    
    
  "usingComponents": {
    
    
    "imgModule":"/components/global/image/index"
  }
}

Subcomponent receives

// 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
              })
            }
          })
        }
      }
    }
  },
})

2. The child component calls the function of the parent component and passes the value to the parent component

// 子组件
this.triggerEvent("gotoDetail", {
    
    id:"id"})
// 父组件
<newsList id="newsList" bindgotoDetail="handleGotoNewsDetail"></newsList>

3. The parent component calls the value and function of the child component

// 父组件
<newsList id="newsList" listArr="{
     
     {culturalList}}" bindgotoDetail="handleGotoNewsDetail"></newsList>
// 父组件直接获取子组件的数据
this.selectComponent('#newsList')
this.selectComponent('#newsList').gotoDetailById() // 父组件调子组件的函数 
this.selectComponent('#newsList').data.listArr // 父组件调子组件的值

Guess you like

Origin blog.csdn.net/weixin_45665171/article/details/128983354