溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

微信小程序怎么使用自定義組件封裝原生image組件

發(fā)布時間:2022-03-11 10:39:03 來源:億速云 閱讀:328 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細介紹“微信小程序怎么使用自定義組件封裝原生image組件 ”,內(nèi)容詳細,步驟清晰,細節(jié)處理妥當,希望這篇“微信小程序怎么使用自定義組件封裝原生image組件 ”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。

常規(guī)操作

在小程序沒還沒推出自定義組件功能時,只能通過改變 Page 中的 data 來展示兜底的占位圖,所以當時的處理方式十分蛋疼...

1.1.相同默認圖

由于需要知道這個圖片的數(shù)據(jù)路徑,所以不得不在每個 image 上加上類似 data-img-path 的東西。

<view
    wx:for="{{ obj.arr }}"
    wx:key="imgSrc"
    wx:for-item="item"
    wx:for-index="itemIdx"
><image
        src="{{ item.imgSrc }}"
        binderror="onImageError"
        data-img-path="obj.arr[{{ itemIdx }}].imgSrc"
    />
</view>
復(fù)制代碼
const DEFAULT_IMG = '/assets/your_default_img'

Page({
    data: {
        obj: {
            arr: [
                { imgSrc: 'your_img1' },
                { imgSrc: 'your_img2' },
            ],
        },
    },
    onImageError ({
        target: { dataset: { imgPath } },
    }) {
        this.setData({
            [imgPath]: DEFAULT_IMG,
        })
    },
})
復(fù)制代碼

1.2.不同默認圖

如果默認圖片不同呢?例如球員、球隊和 feed 的默認圖片一般都是不同的。

那么一般只好再增加一個屬性例如 data-img-type 來標識默認圖的類型。

<!-- 球隊圖 -->
<image
    ...
    data-img-type="team"
/>
<!-- 球員圖 -->
<image
    ...
    data-img-type="player"
/>
復(fù)制代碼
const DEFAULT_IMG_MAP = {
    feed: '/assets/default_feed',
    team: '/assets/default_team',
    player: '/assets/default_player',
}

Page({
    data: {
        obj: {
            arr: [
                { imgSrc: 'your_img1' },
                { imgSrc: 'your_img2' },
            ],
        },
    },
    onImageError ({
        target: { dataset: { imgPath, imgType } },
    }) {
        this.setData({
            [imgPath]: DEFAULT_IMG_MAP[imgType],
        })
    },
})
復(fù)制代碼

1.3.圖片在模板中

頁面層級淺倒還好,如果跨模板了,那么模板就可能要用一個類似于 pathPrefix 的屬性來傳遞模板數(shù)據(jù)的路徑前綴。

<!--
    球員排行模板
    pathPrefix: String
    playerList: Array
    ...
-->
<template name="srPlayerRank"><view
        wx:for="{{ playerList }}"
        wx:key="imgSrc"
        wx:for-item="item"
        wx:for-index="itemIdx"
    ><image
            src="{{ item.imgSrc }}"
            binderror="onImageError"
            data-img-type="player"
            data-img-path="{{ pathPrefix }}.playerList[{{ itemIdx }}].imgSrc"
        /></view>
</template>
復(fù)制代碼

最后在失敗回調(diào)里調(diào)用 setData({ [path]: DEFAULT_IMG }) 重新設(shè)置圖片地址。

自定義組件

2.1.原生自定義組件

原生寫法一般要寫4個文件:.json/.wxml/.js/.wxss

  • TuaImage.json

{
    "component": true
}
復(fù)制代碼
  • TuaImage.wxml

<!-- 加載中的圖片 -->
<image
    hidden="{{ !isLoading }}"
    src="{{ errSrc }}"
    style="width: {{ width }}; height: {{ height }}; {{ styleStr }}"
    mode="{{ imgMode }}"
/>


<!-- 實際加載的圖片 -->
<image
    hidden="{{ isLoading }}"
    src="{{ imgSrc || src }}"
    mode="{{ imgMode }}"
    style="width: {{ width }}; height: {{ height }}; {{ styleStr }}"
    bindload="_onImageLoad"
    binderror="_onImageError"
    lazy-load="{{ true }}"
/>
復(fù)制代碼
  • TuaImage.js

const DEFAULT_IMG = '/assets/your_default_img'

Component({
    properties: {
        // 圖片地址
        src: String,
        // 圖片加載中,以及加載失敗后的默認地址
        errSrc: {
            type: String,
            // 默認是球隊圖標
            value: DEFAULT_IMG,
        },
        width: {
            type: String,
            value: '48rpx',
        },
        height: {
            type: String,
            value: '48rpx',
        },
        // 樣式字符串
        styleStr: {
            type: String,
            value: '',
        },
        // 圖片裁剪、縮放的模式(詳見文檔)
        imgMode: {
            type: String,
            value: 'scaleToFill',
        },
    },
    data: {
        imgSrc: '',
        isLoading: true,
    },
    methods: {
        // 加載圖片出錯
        _onImageError (e) {
            this.setData({
                imgSrc: this.data.errSrc,
            })
            this.triggerEvent('onImageError', e)
        },
        // 加載圖片完畢
        _onImageLoad (e) {
            this.setData({ isLoading: false })
            this.triggerEvent('onImageLoad', e)
        },
    },
})
復(fù)制代碼

布吉島大家使用原生寫法時有木有一些感覺不方便的地方:

  • 4個文件:.json/.wxml/.js/.wxss,這樣老需要切來切去的降低效率

  • properties 是什么鬼?大家(React/Vue)一般不都用 props 么?

  • style="width: {{ width }}; height: {{ height }}; {{ styleStr }}" 樣式字符串怎么辣么長...

2.2.TuaImage.vue

所以以下是一個使用單文件組件封裝原生 image 組件的例子。

  • 使用單文件組件將配置、模板、腳本、樣式寫在一個文件中,方便維護。

  • 使用計算屬性 computed 將樣式字符串寫在 js 中。

  • 使用 this.imgSrc = this.errSrc 而不是 this.setData 來改變 data。

<config>
{
    "component": true
}
</config>

<template lang="wxml"><!-- 加載中的圖片 --><image
        hidden="{{ !isLoading }}"
        src="{{ errSrc }}"
        style="{{ imgStyleStr }}"
        mode="{{ imgMode }}"
    /><!-- 實際加載的圖片 --><image
        hidden="{{ isLoading }}"
        src="{{ imgSrc || src }}"
        mode="{{ imgMode }}"
        style="{{ imgStyleStr }}"
        bindload="_onImageLoad"
        binderror="_onImageError"
        lazy-load="{{ true }}"
    />
</template>

<script>
/**
 * 圖片組件,能夠傳遞備用圖片以防圖片失效
 * https://developers.weixin.qq.com/miniprogram/dev/component/image.html
 */

// 也可以設(shè)置為網(wǎng)絡(luò)圖片如: https://foo/bar.png
const DEFAULT_IMG = '/assets/your_default_img'

export default {
    props: {
        // 圖片地址
        src: String,
        // 圖片加載中,以及加載失敗后的默認地址
        errSrc: {
            type: String,
            // 默認是球隊圖標
            default: DEFAULT_IMG,
        },
        width: {
            type: String,
            default: '48rpx',
        },
        height: {
            type: String,
            default: '48rpx',
        },
        // 樣式字符串
        styleStr: {
            type: String,
            default: '',
        },
        // 圖片裁剪、縮放的模式(詳見文檔)
        imgMode: {
            type: String,
            default: 'scaleToFill',
        },
    },
    data () {
        return {
            imgSrc: '',
            isLoading: true,
        }
    },
    computed: {
        // 樣式字符串
        imgStyleStr () {
            return `width: ${this.width}; height: ${this.height}; ${this.styleStr}`
        },
    },
    methods: {
        // 加載圖片出錯
        _onImageError (e) {
            this.imgSrc = this.errSrc
            this.$emit('onImageError', e)
        },
        // 加載圖片完畢
        _onImageLoad (e) {
            this.isLoading = false
            this.$emit('onImageLoad', e)
        },
    },
}
</script>

<style lang="scss">

</style>
復(fù)制代碼

讀到這里,這篇“微信小程序怎么使用自定義組件封裝原生image組件 ”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI