1. 程式人生 > 實用技巧 >LinUI學習8 新監聽器observers與自定義hot-list元件

LinUI學習8 新監聽器observers與自定義hot-list元件

LinUI學習8 新監聽器observers與自定義hot-list元件

1、定義一個hot-list元件

在component檔案加下新建一個hot-list元件,

在對應的page的json中當前是在home.js中引入該元件

{
  "usingComponents": {
    "s-hot-list":"/components/hot-list/index"
  }
}

2、Http請求獲取資訊

在model資料夾下的banner.js中編寫

const { Http } = require("../utils/http") //這是之前封裝好的公共Http請求 詳情見前面的筆記

class Banner{
  static locationG 
= 'b-2' static async getHomeLocationG(){ return await Http.request({ url:`/banner/name/${Banner.locationG}` }) } } export{ Banner }

在home.js呼叫該請求

 const bannerG = await Banner.getHomeLocationG()

 that.setData({
      BannerB:bannerB,
      BannerG:bannerG,
    })

呼叫該元件並將請求獲得的資料傳到元件中

  <s-hot-list banner="{{BannerG}}"></s-hot-list>

3、編寫元件hot-list

我們獲取到的資料如下

將items展開

因此我們需要根據將items內的name來確定圖片放置的位子,因此我們需要在js中使用到新版的監聽器 observers

hot-list.js

// components/hot-list/index.js
Component({
  /**
   * 元件的屬性列表
   */
  properties: {
    banner:Object //接收傳入
  },
  observers:{       
//監聽器 'banner':function(banner){ if(!banner){ return } if(banner.items.length === 0){ return } const left = banner.items.find(i=>i.name==='left') const rightTop =banner.items.find(i=> i.name==='right-top') const rightBottom = banner.items.find(i=> i.name==='right-bottom') this.setData({ left:left, rightTop:rightTop, rightBottom:rightBottom, }) } }, /** * 元件的初始資料 */ data: { left:'', rightTop:'', rightBottom:'', }, /** * 元件的方法列表 */ methods: { } })

hot-list.wxml

<view class="container">
  <image src="{{banner.img}}"></image>
  <view class="inner-container">
    <image src="{{left.img}}"></image>
    <image src="{{rightTop.img}}"></image>
    <image src="{{rightBottom.img}}"></image>
  </view>
</view>

完善一下css就可以實現該功能了。