方法1:
<template>
<view class="content">
<view class="text-area">
<text class="title">{{title}}</text>
<button type="default" @click="chooseImg">上传图片</button>
</view>
<!-- 上传的图片渲染到页面 -->
<image v-for="item in img" :src="item" mode=""></image>
</view>
</template>
<script>
export default {
data() {
return {
title: "首页",
img: []
}
},
onLoad() {},
methods: {
chooseImg() {
//该方法会自动打开文件,我们就可以上传我们想要的图片
uni.chooseImage({
count: 5,//最多可以上传几张图片
success: res => {
console.log(res)
this.img = res.tempFilePaths
}
})
}
},
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>
效果:
count可以决定我们要上传几张图片(只决定微信小程序的,决定不了浏览器的),浏览器和微信小程序有一点区别。浏览器可上传多张图片并进行预览,但是在微信小程序中打开最多只能一次上传5张图片,具体如下图。
-
浏览器
-
微信小程序
方法2
uni-app默认的方法uni.previewImage,该方法可以选择预览具体某一张图片。代码和效果图如下:
<template>
<view class="content">
<view class="text-area">
<text class="title">{{title}}</text>
<button type="default" @click="chooseImg">上传图片</button>
</view>
<!-- 上传的图片渲染到页面 -->
<image v-for="item in img" :src="item" mode="" @click="previewImg(item)"></image>
</view>
</template>
<script>
export default {
data() {
return {
title: "首页",
img: []
}
},
onLoad() {},
methods: {
chooseImg() {
uni.chooseImage({
count: 5,
success: res => {
console.log(res)
this.img = res.tempFilePaths
}
})
},
previewImg(current){
console.log(current);
uni.previewImage({
current:current,//当前点击的图片
urls:this.img,//上传的图片
// 注意,下面两个属性只在h5和APP才有用
loop:true,//自动轮播
indicator:"number"//default为滑动时底部圆点,number为滑动时为数字
})
}
},
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>
这里我点击了购物车图片,该图片默认占全屏预览。这里还可以进行滑动(左右滑动)查看其他图片。