作者:yiyizym,原文地址
本文介紹微信小程序 (自制)上傳圖片組件 的關(guān)鍵實現(xiàn),喜歡通過代碼學(xué)習(xí)的朋友,可以直接看源碼
緣由
最近在微信小程序上要實現(xiàn)上傳圖片的功能,因為多個頁面都會用到這個功能,我試著就像網(wǎng)頁開發(fā)一樣,寫一個能復(fù)用的組件。
上傳圖片的功能,微信小程序已經(jīng)提供了相應(yīng)的組件和API,結(jié)合 weui 樣式,如果不考慮復(fù)用的話,很容易實現(xiàn)(官方 demo 就可以拿來用 ^_^ )。
如果要復(fù)用,可以利用模板,但是會面臨微信小程序的很多限制。
限制
舉個例子,下面是一個模板文件 customer.wxml ( 注意模板文件里綁定了一個回調(diào)函數(shù) sayHello )
-
<template name="customer" data-customerid="{{ id }}" bindtap="sayHello">
-
<text>{{ name }}</text>
-
<text>{{ gender }}</text>
-
<text>{{ age }}</text>
-
<block wx:for="orders" wx:for-item="order">
-
<view>{{order.id}}</view>
-
<view>{{order.detail}}</view>
-
</block>
-
</template>
頁面 A.wxml 引用了這個模板文件 :
-
<import src="path/to/customer.wxml">
-
<template is="customer" data="{{...customer}}"></template>
如果要顯示模板里的 orders 部分,頁面 A 的 js 文件里 data 必須有一個名為customer 的 key (可以通過 setData 設(shè)置 name/gender/age ,但不能通過setData 設(shè)置 orders ,這樣會報錯。猜測是因為 setData 在模板解析之后執(zhí)行,解析模板時 name/gender/age/orders 都為 undefined ,name/gender/age 為 undefined 時不顯示就行,但 wx:for 會遍歷 orders ,遍歷時調(diào)用 hasOwnProperty 方法,這時就報錯了。),如果要調(diào)用模板里的回調(diào)函數(shù) sayHello ,同樣必須在頁面 A 的 js 文件里先定義它:
-
// A.js
-
Page({
-
data: {
-
customer: {} // 可以先寫成空 hash ,稍后更新,但 key 必須先存在
-
},
-
sayHello: function(e){
-
// say hello
-
// e.target.dataset.customerid
-
}
-
})
解決辦法 因為這兩個限制,必須找出一個辦法讓模板文件能動態(tài)改變引用它的文件(以下稱為宿主)的作用域下的一些變量和方法,如下:
-
// A.js
-
require('path/to/customer.js');
-
-
Page({
-
data: {
-
customer: {}
-
}
-
onLoad: function(){
-
// this 是宿主的執(zhí)行上下文環(huán)境
-
// this.data 可以訪問 data
-
// this.setData 可以更新 data
-
// this.func = function() {} 可以往宿主增加新方法
-
new Customer(this);
-
}
-
})
-
// customer.js
-
// 這里用到 es6 的類定義語法
-
-
class Customer {
-
constructor(pageContext){
-
this.page = pageContext
-
this.page.sayHello = this.sayHello
-
}
-
-
sayHello(e){
-
// say hello
-
// e.target.dataset.customerid
-
}
-
}
-
-
module.exports = Customer
本文關(guān)于微信小程序的組件開發(fā)關(guān)鍵點介紹完畢,源碼 還展示了如何 設(shè)置組件的默認配置以及更改組件的回調(diào)方法。
|