写一个微信小程序上传图片和视频将数据放进一个数组里传给父组件详细代码
时间: 2023-12-06 14:45:32 浏览: 31
微信小程序上传图片和视频可以使用`wx.chooseImage`和`wx.chooseVideo`方法,将数据放进一个数组里可以使用`Array.push`方法,传给父组件可以使用`this.triggerEvent`方法。下面是详细代码:
1. 在wxml文件中添加上传按钮
```html
<button bindtap="chooseImage">选择图片</button>
<button bindtap="chooseVideo">选择视频</button>
<button bindtap="uploadData">上传数据</button>
```
2. 在js文件中添加选择图片和视频的方法
```javascript
Page({
data: {
imageList: [], // 选中的图片
videoList: [], // 选中的视频
},
chooseImage() {
wx.chooseImage({
success: (res) => {
const tempFilePaths = res.tempFilePaths
this.setData({
imageList: this.data.imageList.concat(tempFilePaths) // 将选中的图片存入数组
})
}
})
},
chooseVideo() {
wx.chooseVideo({
success: (res) => {
const tempFilePath = res.tempFilePath
this.setData({
videoList: this.data.videoList.concat(tempFilePath) // 将选中的视频存入数组
})
}
})
},
})
```
3. 在js文件中添加上传数据的方法
```javascript
Page({
data: {
imageList: [],
videoList: [],
},
uploadData() {
const { imageList, videoList } = this.data
const data = { imageList, videoList }
this.triggerEvent('upload', data) // 将选中的图片和视频传给父组件
},
})
```
4. 在父组件中监听上传事件并处理数据
```html
<!-- 父组件wxml文件 -->
<child-component bind:upload="handleUpload"></child-component>
```
```javascript
// 父组件js文件
Page({
handleUpload(e) {
const { imageList, videoList } = e.detail // 获取子组件传来的数据
// 处理数据
},
})
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)