注册登录

微信小程序上传图片组件及如何上传多张图片

2020-09-28
导读:2017年6月14日,微信小程序上传图片组件已经是当下最热门的话题,下面将从多方面来谈谈微信小程序上传图片的内容。...

微信小程序上传图片组件已经是当下最热门的话题,下面将从多方面来谈谈微信小程序上传图片的内容。

最近在微信小程序上要实现上传图片的功能,因为多个页面都会用到这个功能,我试着就像网页开发一样,写一个能复用的组件。

上传图片的功能,微信小程序已经提供了相应的组件和API,结合 weui 样式,如果不考虑复用的话,很容易实现(官方 demo 就可以拿来用 ^_^ )。

如果要复用,可以利用模板,但是会面临微信小程序的很多限制。

限制

举个例子,下面是一个模板文件 customer.wxml ( 注意模板文件里绑定了一个回调函数 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 设置 name/gender/age ,但不能通过 setData 设置 orders ,这样会报错。猜测是因为setData 在模板解析之后执行,解析模板时 name/gender/age/orders 都为 undefined ,name/gender/age 为 undefined 时不显示就行,但 wx:for 会遍历 orders ,遍历时调用 hasOwnProperty 方法,这时就报错了。),如果要调用模板里的回调函数 sayHello ,同样必须在页面 A 的 js 文件里先定义它:

 

// A.js
Page({
data: {
  customer: {} // 可以先写成空 hash ,稍后更新,但 key 必须先存在
},
sayHello: function(e){
  // say hello
  // e.target.dataset.customerid
}
})

解决办法

因为这两个限制,必须找出一个办法让模板文件能动态改变引用它的文件(以下称为宿主)的作用域下的一些变量和方法,如下:

 

// A.js
require('path/to/customer.js');

Page({
data: {
  customer: {}
}
onLoad: function(){
  // this 是宿主的执行上下文环境
  // 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

 


重磅推荐:小程序开店目录

第一部分:小商店是什么

第二部分:如何开通一个小商店

第三部分:如何登录小商店

第四部分:开店任务常见问题

第五部分:小商店可以卖什么

第六部分:HiShop小程序特色功能

第七部分:小程序直播

第八部分:小程序收货/物流

第九部分:小程序怎么结算

第十部分:小程序客服

第十一部分:电商创业

第十二部分:小程序游戏开发

电话咨询 微信咨询 预约演示 0元开店