# 一、发图片功能
从本地相册选择图片或使用相机拍照,具体查看官网:https://uniapp.dcloud.net.cn/api/media/image.html#chooseimage (opens new window)
很明显发图片需要打开相册,因此需要授权相册权限。
# 1. 关于获取权限的重要说明
- 我们开发的H5端、小程序、app包括(安卓、ios、鸿蒙)最后都是要上线到各个应用市场,而能够上线通过审核最关键的一点就是你的权限是否合法合规,各个应用市场对权限的申请原则都是:最小权限原则,需要用到时候才申请,也就是说
你申请的权限必须是你app实际需要的权限,不要在程序一开始都要求用户授权,需要明确告知权限的用途,不能多申请,否则审核不通过。
# 2. 封装一个权限类用来处理权限的申请、设置、检查、提示
封装一个权限类 :/common/mixins/uni_permission.js
内容过多,在新页面打开,具体查看:uni_permission.js权限申请类(支持多端)
# 3. 在页面调用并申请权限
# ① 安卓端app需要在 App.vue 中添加以下代码
...
<script>
export default {
onLaunch: function() {
console.log('App Launch')
...
// 监听应用状态变化
// #ifdef APP-PLUS
let appHideTime = 0;
plus.globalEvent.addEventListener('pause', () => {
console.log('应用进入后台');
appHideTime = Date.now();
uni.$emit('app_hide');
});
plus.globalEvent.addEventListener('resume', () => {
console.log('应用回到前台');
const hideDuration = Date.now() - appHideTime;
console.log(`应用在后台停留时间: ${hideDuration}ms`);
uni.$emit('app_show', { hideDuration });
});
// #endif
},
onShow: function() {
console.log('App Show')
},
onHide: function() {
console.log('App Hide')
}
}
</script>
# ② 页面调用和发送图片
/pages/chat/chat.nvue 调用代码
<template>
<view>
...
</view>
</template>
<script>
import UniPermission from '@/common/mixins/uni_permission.js';
import toolJs from '@/common/mixins/tool.js';
export default {
mixins:[toolJs],
...,
methods: {
...,
// 点击菜单项处理
async swiperItemClick(item, itemIndex) {
console.log('点击菜单项处理',item);
if (!item) return; // 防止undefined错误
if (this.sendMessageMode === 'icon') {
...
} else {
...
switch (item.eventType){
case 'photo': // 照片功能
await this.handlePhoto();
break;
case 'map': // 位置功能
await this.handleLocation();
break;
case 'camera': // 拍摄功能
await this.handleCamera();
break;
case 'mingpian':
break;
case 'video':
break;
}
}
},
// 处理相册照片
async handlePhoto() {
try {
const permission = new UniPermission();
const granted = await permission.requestPermission(
'photo',
'需要访问您的相册来选择照片',
'本功能需要您打开相册'
);
if (granted) {
console.log('相册权限已授予,开始选择图片');
this.chooseImage();
// setTimeout(() => {this.chooseImage();}, 300);
} else {
uni.showToast({ title: '无相册权限', icon: 'none',duration: 2000});
}
} catch (error) {
console.error('权限申请异常:', error);
uni.showToast({
title: '权限申请失败: ' + error.message,
icon: 'none',
duration: 3000
});
}
},
// 选择图片
chooseImage() {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album'],
success: (res) => {
if (res.tempFilePaths && res.tempFilePaths.length > 0) {
this.sendMessage('image', { path: res.tempFilePaths[0] });
}
},
fail: (err) => {
console.error('选择图片失败:', err);
let errorMsg = '选择图片失败';
if (err.errMsg.includes('permission')) {
errorMsg = '相册访问权限不足';
} else if (err.errMsg.includes('cancel')) {
return; // 用户取消不提示
}
uni.showToast({
title: errorMsg,
icon: 'none',
duration: 2000
});
}
});
},
// 处理位置权限
async handleLocation() {
try {
const permission = new UniPermission();
const granted = await permission.requestPermission(
'location',
'需要访问您的位置以获取当前位置信息'
);
if (granted) {
//this.getLocation();
}
} catch (error) {
console.error('位置权限申请失败:', error);
}
},
// 处理相机权限
async handleCamera() {
try {
const permission = new UniPermission();
const granted = await permission.requestPermission(
'camera',
'需要访问您的相机以进行拍摄'
);
if (granted) {
//this.openCamera();
}
} catch (error) {
console.error('相机权限申请失败:', error);
}
},
...,
//发送消息
sendMessage(msgType, option = {}){
...
switch (msgType){
case 'text':
...
break;
case 'iconMenus':
...
break;
case 'image':
console.log('image的数据',option);
msg.data = option.path;
}
...
},
},
}
</script>
# ③ 图片展示
在组件 /components/chat-item/chat-item.vue
<template>
<view class="px-3">
<!-- 时间 -->
...
<!-- 撤回消息 -->
...
<!-- 聊天内容 -->
<view v-else
...>
<!-- 好友 -->
<!-- 头像 -->
...
<!-- 气泡 -->
<!-- 三角形 -->
...
<!-- 内容 -->
<view ...>
<!-- 情况1:表情里面的图片 -->
<view v-if="item.type == 'iconMenus' &&
item.dataType && item.dataType == 'image'">
<u--image showLoading showMenuByLongpress
:src="item.data" mode="widthFix"
width="200rpx" height="200rpx" radius="10rpx"></u--image>
</view>
<!-- 情况2: 发图片 -->
<view v-else-if="item.type == 'image'">
<u--image showLoading showMenuByLongpress
:src="item.data" mode="widthFix"
width="260rpx" height="150px" radius="10rpx"></u--image>
</view>
<!-- 文字 -->
<text v-else
class="font" style="text-align: justify;">
{{item.data}}
</text>
</view>
<!-- 我 -->
...
</view>
<!-- 弹出菜单 -->
...
</view>
</template>
# 二、发多张图片及预览
具体看官网,预览图片:https://uniapp.dcloud.net.cn/api/#媒体 (opens new window)
# 1. 组件处理
在组件: /components/chat-item/chat-item.vue
<template>
<view class="px-3">
<!-- 时间 -->
...
<!-- 撤回消息 -->
...
<!-- 聊天内容 -->
<view v-else ...>
<!-- 好友 -->
<!-- 头像 -->
...
<!-- 气泡 -->
<!-- 三角形 -->
...
<!-- 内容 -->
<view ...>
<!-- 情况1: 表情包里面的gif/png图片 -->
<view ...>
<u--image
...
@click="previewImage(item,index)"></u--image>
</view>
<!-- 情况2: 发图片 -->
<view ...>
<u--image mode="aspectFill"
... radius="10rpx"
@click="previewImage(item,index)"></u--image>
</view>
<!-- 文字 -->
...
</view>
<!-- 我 -->
...
</view>
...
</view>
</template>
<script>
...
export default{
...,
methods:{
//预览图片
previewImage(item,index){
console.log('预览图片',item);
// 预览一张
// uni.previewImage({
// urls:[item.data]
// });
// 预览选择的多张图片
this.$emit('previewImages',{
item,
index
});
},
...,
}
}
</script>
# 2. 在页面处理
/pages/chat/chat.nvue 页面
<template>
<view>
<!-- 导航栏 -->
...
<!-- 聊天内容区域 -->
<scroll-view ...>
<!-- 对话部分 -->
<view ...>
<chat-item ... @previewImages="previewImages"></chat-item>
</view>
</scroll-view>
<!-- 针对我们的app端点击聊天区域授权加号扩展菜单 -->
...
<!-- 底部聊天输入区域 -->
...
<!-- 弹出菜单 -->
...
</view>
</template>
<script>
...
export default {
...,
computed:{
...,
// 多图预览图片地址数组集合
previewImagesList(){
let arr = [];
this.chatDataList.forEach(item =>{
if(item.type == 'image' || (item.type == 'iconMenus' &&
item.dataType && item.dataType == 'image')){
arr.push(item.data);
}
});
return arr;
},
},
methods: {
...,
//选择照片发送
chooseImage(){
uni.chooseImage({
count:9,
//sizeType:['original','compressed'],
sourceType:['album'],
success: (res) => {
console.log('选择照片res',res);
if(res.tempFilePaths && res.tempFilePaths.length){
// 发送到服务器或者第三方云存储
// 页面展示
// 单张
// this.sendMessage('image',{path:res.tempFilePaths[0]});
// 多张
res.tempFilePaths.forEach(item=>{
this.sendMessage('image',{path:item});
});
}
},
fail: (err) => {
...
}
});
},
//预览图片
previewImages(e){
console.log('页面预览图片',e);
uni.previewImage({
urls:this.previewImagesList,
current:e.item.data,
indicator:'default',
});
},
...,
},
}
</script>
# 三、【选修】发图片自适应宽高显示
我们目前用的是uviewUI提供的
u--image组件,只能给固定宽高,有同学希望发送的图片显示的时候是自适应宽高,那么我们可以这么来做。
# 1. 简单的按照最大宽度或者最大高度来处理
在组件: /components/chat-item/chat-item.vue
<template>
<view class="px-3">
<!-- 时间 -->
...
<!-- 撤回消息 -->
...
<!-- 聊天内容 -->
<view ...>
<!-- 好友 -->
<!-- 头像 -->
...
<!-- 气泡 -->
<!-- 三角形 -->
...
<!-- 内容 -->
<view ...>
<!-- 情况1: 表情包里面的gif/png图片 -->
<view v-if="item.type == 'iconMenus' &&
item.dataType && item.dataType == 'image'">
<!-- nvue页面组件u--image的load事件有兼容问题 -->
<!-- <u--image
:src="item.data" mode="widthFix"
width="200rpx" height="200rpx" radius="10rpx"
@click="previewImage(item,index)"
@load="handleImageLoad($event, item,index)"></u--image> -->
<image lazy-load mode="widthFix"
:src="item.data"
:style="imageShowStyle"
class="rounded"
@click="previewImage(item,index)"
@load="handleImageLoad($event,item,index)"></image>
</view>
<!-- 情况2: 发图片 -->
<view v-else-if="item.type == 'image'">
<!-- nvue页面组件u--image的load事件有兼容问题 -->
<!-- <u--image showMenuByLongpress showLoading
:src="item.data" mode="aspectFill"
width="260rpx" height="150px" radius="10rpx"
@click="previewImage(item,index)"
@load="handleImageLoad($event, item,index)"></u--image> -->
<image lazy-load mode="widthFix"
:src="item.data"
:style="imageShowStyle"
class="rounded"
@click="previewImage(item,index)"
@load="handleImageLoad($event,item,index)"></image>
</view>
<!-- 文字 -->
...
</view>
<!-- 我 -->
...
</view>
<!-- 弹出菜单 -->
...
</view>
</template>
<script>
...,
export default{
...,
data(){
return {
...,
// 图片显示宽高
width:120,
height:120,
}
},
computed:{
...,
// 图片展示的等比例展示
imageShowStyle(){
return `width: ${this.width}px;height: ${this.height}px;`;
},
},
methods:{
// 加载预览图片
handleImageLoad(e,item,index){
console.log('加载预览图片',e);
console.log('加载预览图片index,index',item,index);
let width = e.detail.width;
let height = e.detail.height;
//聊天界面显示最大宽度
let maxWidth = uni.upx2px(300);
// 按最大宽度300rpx 计算最大可显示的高度
// if(width <= maxWidth){
// // 实际宽高展示
// this.width = width;
// this.height = height;
// return;
// }
// // 进行比例计算, 等比例缩放
// //width / height = maxWidth / maxHeight;
// let maxHeight = maxWidth * (height / width);
// this.width = maxWidth;
// this.height = maxHeight;
// 按最大高度400rpx 计算可以显示的最大宽度
// let maxHeight = uni.upx2px(400);
// if(height < maxHeight && width <= maxWidth){
// // 实际宽高展示
// this.width = width;
// this.height = height;
// return;
// }
// this.height = maxHeight;
// // height / width = maxHeight / maxWidth;
// this.width = maxHeight * (width / height);
// 需要考虑 当图片达到最大高度,计算的宽度也超过最大宽度
let maxHeight = uni.upx2px(400);
if(height < maxHeight){
// 实际宽高展示
this.width = width <= maxWidth ? width : maxWidth;
this.height = height;
return;
}
this.height = maxHeight;
// height / width = maxHeight / maxWidth;
let _width = maxHeight * (width / height);
this.width = _width <= maxWidth ? _width : maxWidth;
},
...
}
}
</script>
# 2. 考虑更多图片大小情况的优化方案
在组件: /components/chat-item/chat-item.vue
<template>
<view class="px-3">
<!-- 时间 -->
...
<!-- 撤回消息 -->
...
<!-- 聊天内容 -->
<view ...>
<!-- 好友 -->
<!-- 头像 -->
...
<!-- 气泡 -->
<!-- 三角形 -->
...
<!-- 内容 -->
<view ...>
<!-- 情况1: 表情包里面的gif/png图片 -->
<view v-if="item.type == 'iconMenus' &&
item.dataType && item.dataType == 'image'">
<!-- nvue页面组件u--image的load事件有兼容问题 -->
<!-- <u--image
:src="item.data" mode="widthFix"
width="200rpx" height="200rpx" radius="10rpx"
@click="previewImage(item,index)"
@load="handleImageLoad(e, item,index)"></u--image> -->
<!-- <image lazy-load mode="widthFix"
:src="item.data"
:style="imageShowStyle"
class="rounded"
@click="previewImage(item,index)"
@load="handleImageLoad($event,item,index)"></image> -->
<image lazy-load :mode="imageMode"
:src="item.data"
:style="getImageStyle(index)"
class="rounded"
@click="previewImage(item,index)"
@load="handleImageLoad($event,item,index)"></image>
</view>
<!-- 情况2: 发图片 -->
<view v-else-if="item.type == 'image'">
<!-- nvue页面组件u--image的load事件有兼容问题 -->
<!-- <u--image showMenuByLongpress showLoading
:src="item.data" mode="aspectFill"
width="260rpx" height="150px" radius="10rpx"
@click="previewImage(item,index)"
@load="handleImageLoad(e, item,index)"></u--image> -->
<!-- <image lazy-load mode="widthFix"
:src="item.data"
:style="imageShowStyle"
class="rounded"
@click="previewImage(item,index)"
@load="handleImageLoad($event,item,index)"></image> -->
<image lazy-load :mode="imageMode"
:src="item.data"
:style="getImageStyle(index)"
class="rounded"
@click="previewImage(item,index)"
@load="handleImageLoad($event,item,index)"></image>
</view>
<!-- 文字 -->
...
</view>
<!-- 我 -->
...
</view>
<!-- 弹出菜单 -->
...
</view>
</template>
<script>
...,
export default{
...,
data(){
return {
...,
imageSizes: {}, // 存储每个图片的计算尺寸
imageMode: 'widthFix' // 图片模式
}
},
computed:{
...,
},
methods:{
// 加载预览图片 - 优化后的尺寸计算
handleImageLoad(e, item, index) {
const { width: originWidth, height: originHeight } = e.detail;
const maxWidth = uni.upx2px(300); // 最大宽度300rpx转px
const maxHeight = uni.upx2px(400); // 最大高度400rpx转px
// 计算缩放比例
const widthRatio = maxWidth / originWidth;
const heightRatio = maxHeight / originHeight;
const ratio = Math.min(widthRatio, heightRatio, 1); // 取最小比例且不超过1
// 计算最终尺寸
let width = originWidth * ratio;
let height = originHeight * ratio;
// 确保尺寸不超过最大值
if (width > maxWidth) width = maxWidth;
if (height > maxHeight) height = maxHeight;
// 存储计算后的尺寸
this.$set(this.imageSizes, index, {
width,
height
});
// 设置图片模式:宽>高时使用aspectFit,否则使用widthFix
if (originWidth > originHeight) {
this.imageMode = 'aspectFit';
} else {
this.imageMode = 'widthFix';
}
},
// 获取图片样式
getImageStyle(index) {
const size = this.imageSizes[index] || {};
return {
width: size.width ? `${size.width}px` : '120px',
height: size.height ? `${size.height}px` : '120px'
};
},
...,
}
}
</script>
# 3. 封装成组件(全部代码)
- 新建组件
/components/chat-item-image/chat-item-image.vue
<template>
<view>
<!-- <u--image showMenuByLongpress showLoading
:src="item.data" mode="aspectFill"
width="260rpx" height="150px" radius="10rpx"
@click="previewImage(item,index)"
@load="handleImageLoad($event,item,index)"></u--image> -->
<!-- <image :src="item.data"
lazy-load mode="widthFix"
:style="imageShowStyle"
class="rounded"
@click="previewImage(item,index)"
@load="handleImageLoad($event,item,index)"></image> -->
<image lazy-load :mode="imageMode"
:src="item.data"
:style="getImageStyle(index)"
:class="imageClass"
@click="$emit('click')"
@load="handleImageLoad($event,item,index)"></image>
</view>
</template>
<script>
export default {
name:"chat-item-image",
props:{
item:Object,
index:Number,
//最大宽度
maxWidth:{
type:Number,
default:300 //300rpx
},
//最大高度
maxHeight:{
type:Number,
default:400 //400rpx
},
// class
imageClass:{
type:String,
default:'rounded',
},
},
data(){
return {
// 消息图
width:120,
height:120,
imageSizes: {}, // 存储每个图片的计算尺寸
imageMode: 'widthFix' // 图片模式
}
},
computed:{
// 图片等比例展示
imageShowStyle(){
return `width:${this.width}px;height: ${this.height}px;`;
},
},
methods:{
// 加载预览图片并做自适应处理
// handleImageLoad(e,item,index){
// console.log('加载预览图片event',e);
// console.log('加载预览图片item,index',item,index);
// let width = e.detail.width;
// let height = e.detail.height;
// // 聊天界面显示图片 定义一个最大宽度300rpx
// let maxWidth = uni.upx2px(300);
// // 按照最大宽度300rpx 计算最大可显示的高度
// // if(width <= maxWidth){
// // //就用实际宽高
// // this.width = width;
// // this.height = heigth;
// // return;
// // }
// // this.width = maxWidth;
// // //width / height = maxWidth / maxHeight;
// // let maxHeight = maxWidth * (height / width);
// // this.height = maxHeight;
// // 按照最大高度400rpx 来计算一下宽度
// let maxHeight = uni.upx2px(400);
// // if(height <= maxHeight && width <= maxWidth){
// // this.width = width;
// // this.height = heigth;
// // return;
// // }
// // this.height = maxHeight;
// // // height / width = maxHeight / maxWidth;
// // this.width = maxHeight * (width/height);
// // 需要考虑 当图片达到最大高度,计算的宽度也超过最大宽度
// if(height <= maxHeight){
// this.width = width <= maxWidth ? width : maxWidth;
// this.height = heigth;
// return;
// }
// this.height = maxHeight;
// let _width = maxHeight * (width/height);
// this.width = _width <= maxWidth ? _width : maxWidth;
// },
// 优化方案
handleImageLoad(e, item, index) {
const { width: originWidth, height: originHeight } = e.detail;
const maxWidth = uni.upx2px(this.maxWidth); // 最大宽度300rpx转px
const maxHeight = uni.upx2px(this.maxHeight); // 最大高度400rpx转px
// 计算缩放比例
const widthRatio = maxWidth / originWidth;
const heightRatio = maxHeight / originHeight;
const ratio = Math.min(widthRatio, heightRatio, 1); // 取最小比例且不超过1
// 计算最终尺寸
let width = originWidth * ratio;
let height = originHeight * ratio;
// 确保尺寸不超过最大值
if (width > maxWidth) width = maxWidth;
if (height > maxHeight) height = maxHeight;
// 存储计算后的尺寸
this.$set(this.imageSizes, index, {
width,
height
});
// 设置图片模式:宽>高时使用aspectFit,否则使用widthFix
//if (originWidth > originHeight) {
//this.imageMode = 'aspectFit';
//} else {
//this.imageMode = 'widthFix';
//}
},
// 获取图片样式
getImageStyle(index) {
const size = this.imageSizes[index] || {};
return {
width: size.width ? `${size.width}px` : '120px',
height: size.height ? `${size.height}px` : '120px'
};
},
}
}
</script>
<style>
/* #ifdef H5 */
@import '/common/css/common.nvue.vue.css';
/* #endif */
</style>
- 组件
/components/chat-item/chat-item.vue
<template>
<view class="px-3">
<!-- 时间 -->
<view v-if="chatShowTime"
class="flex align-center justify-center pt-2 pb-2">
<text class="font-sm text-light-muted">{{chatShowTime}}</text>
</view>
<!-- 撤回消息 -->
<view v-if="item.isremove"
class="flex align-center justify-center pt-2 pb-2">
<text class="font-sm text-light-muted">您撤回了一条信息</text>
</view>
<!-- 聊天内容 -->
<view v-else
class="flex align-start mb-3 position-relative"
:class="[!isMe ? 'justify-start' : 'justify-end']">
<!-- 好友 -->
<!-- 头像 -->
<u--image v-if="!isMe"
:src="item.avatar"
mode="widthFix"
width="80rpx" height="80rpx" radius="10rpx"></u--image>
<!-- 气泡 -->
<!-- 三角形 -->
<text v-if="!isMe && needQipaoClass"
class="iconfont font-md chat-left-icon"></text>
<!-- 内容 -->
<view class="p-2 rounded"
style="max-width: 500rpx;"
:class="[!isMe ? 'ml-1':'mr-1',`chatItem${index}`,
!isMe && needQipaoClass ? 'chat-left-content-bg pt-2' : 'pt-0',
isMe && needQipaoClass ? 'chat-right-content-bg pt-2' : 'pt-0',]"
:ref="'chatItem' + index"
@longpress="onLongpress($event,index,item)">
<!-- 情况1: 表情包里面的gif/png图片 -->
<view v-if="item.type == 'iconMenus' &&
item.dataType && item.dataType == 'image'">
<chat-item-image :item="item" :index="index"
@click="previewImage(item,index)"
imageClass="rounded"
:maxHeight="300" :maxWidth="300"></chat-item-image>
</view>
<!-- 情况2: 发图片 -->
<view v-else-if="item.type == 'image'">
<chat-item-image :item="item" :index="index"
@click="previewImage(item,index)"
imageClass="rounded"
:maxHeight="400" :maxWidth="300"></chat-item-image>
</view>
<!-- 文字 -->
<text v-else
class="font" style="text-align: justify;">
{{item.data}}
</text>
</view>
<!-- 我 -->
<text v-if="isMe && needQipaoClass"
class="iconfont font-md chat-right-icon"></text>
<u--image v-if="isMe"
:src="item.avatar"
mode="widthFix"
width="80rpx" height="80rpx" radius="10rpx"></u--image>
</view>
<!-- 弹出菜单 -->
<chat-tooltip ref="chatTooltip" :mask="true"
:maskTransparent="true" :isBottom="false"
:tooltipWidth="tooltipWidth"
:tooltipHeight="60"
tooltipClass="bg-dark border-0 text-white">
<view class="flex flex-row flex-1">
<view class="flex-1 align-center justify-center"
hover-class="bg-hover-dark"
v-for="(item,index) in getmenuList" :key="index"
@click="clickType(item.type)">
<text class="text-white">{{item.name}}</text>
</view>
</view>
<!-- 箭头 -->
<text class="position-fixed iconfont text-dark"
style="font-size: 40rpx;"
:style="jiantouStyle"></text>
</chat-tooltip>
</view>
</template>
<script>
import parseTimeJs from '@/common/mixins/parseTime.js';
export default{
name:"chat-item",
mixins:[parseTimeJs],
props:{
item:Object,
index:Number,
//上一条时间
prevTime:[Number,String],
},
data(){
return {
menuEveHeight: 80, //每个菜单默认高度是60rpx
menuList: [{
name: "复制",
type: 'copy'
},
{
name: "撤回",
type: 'removeChatItem'
},
],
tooltipLeft:0, //弹出菜单组件left x
tooltipTop:0, //弹出菜单组件top y
// 组件内容超过这个宽度,菜单居中,
//否则菜单弹出位置由点击位置决定
rectmaxWidth:0,
longpressObj:null, // 存储长按信息内容
}
},
computed:{
// 我的判断, 假设我的id=2,后期由实际数据在更换
isMe(){
let user_id = 2;
return this.item.user_id === user_id;
},
// 显示聊天时间
chatShowTime(){
return parseTimeJs.getChatTime(this.item.chat_time,this.prevTime);
},
tooltipHeight() {
return this.getmenuList.length * this.menuEveHeight;
},
tooltipWidth(){
return this.getmenuList.length * 120;
},
jiantouStyle(){
let left = uni.upx2px(750-40) / 2;
let top = this.tooltipTop + uni.upx2px(40 + 5);
let jiantouCss = ``;
if(this.longpressObj && this.longpressObj.rect.width < this.rectmaxWidth){
top = this.longpressObj.y - 10;
left = this.longpressObj.x + 5;
jiantouCss = `transform:rotate(180deg);`;
}
return `left:${left}px;top:${top}px;${jiantouCss}`;
},
// 弹窗菜单处理
getmenuList(){
return this.menuList.filter(v=>{
if(v.name == '撤回' && !this.isMe){
return false
}
return true;
})
},
// 需要气泡样式
needQipaoClass(){
return this.item.type === 'text' ||
this.item.type === 'audio' ||
(this.item.type === 'iconMenus' && this.item.dataType === 'emoji');
},
},
methods:{
//预览图片
previewImage(item,index){
console.log('预览图片',item);
// 预览单个图片
// uni.previewImage({
// urls:[item.data]
// })
// 预览多张图片
this.$emit('previewImages',{
item,
index
});
},
clickType(e) {
console.log('点击菜单',e);
switch (e){
case 'copy':
break;
case 'removeChatItem':
this.item.isremove = true;
break;
}
this.$refs.chatTooltip.hide();
},
onLongpress(e,index,item){
console.log('组件里面的事件对象',e);
let x = 0,
y = 0;
// #ifdef H5 || MP
x = e.changedTouches[0].clientX;
y = e.changedTouches[0].clientY;
// #endif
// #ifdef APP
x = e.changedTouches[0].screenX;
y = e.changedTouches[0].screenY;
// #endif
/*
this.$emit('Longpress',{
x,
y,
index,
item
});
*/
// #ifdef H5 || MP
const query = uni.createSelectorQuery().in(this);
query.select(`.chatItem${index}`).boundingClientRect(rect=>{
if(rect){
console.log('内容部分距离各个方向',rect);
this.longpressfn({
x,
y,
index,
item,
rect:rect
});
}
}).exec();
// #endif
// #ifdef APP
const refName = 'chatItem' + index;
const ref = this.$refs[refName];
if (!ref) {
console.error('未找到元素引用: ' + refName);
return;
}
// 使用 Weex 的 dom 模块获取位置
const dom = weex.requireModule('dom');
dom.getComponentRect(ref, result => {
if (result && result.result) {
const rect = result.size;
console.log('组件距离各个方向距离:', rect);
this.longpressfn({
x,
y,
index,
item,
rect:rect
});
} else {
console.error('获取位置失败', result);
}
});
// #endif
},
longpressfn(e){
this.longpressObj = e;
console.log('长按得到longpressObj', e);
// 组件内容超过这个宽度,菜单居中,
//否则菜单弹出位置由点击位置决定
this.rectmaxWidth = uni.upx2px((750 - 60 - 80 - (35 + 10 - 5)) / 2);
console.log('内容最大宽度',this.rectmaxWidth);
if(e.rect.width >= this.rectmaxWidth){
this.tooltipLeft = (uni.upx2px(750 - this.tooltipWidth)) / 2;
this.tooltipTop = e.y - uni.upx2px(60 + 40 - 15);
}else{
this.tooltipLeft = e.x;
this.tooltipTop = e.y;
}
this.$refs.chatTooltip.show(this.tooltipLeft, this.tooltipTop);
}
}
}
</script>
<style scoped>
/* #ifdef H5 */
@import '/common/css/common.nvue.vue.css';
/* #endif */
.chat-left-icon{
left:25rpx;top: 20rpx;z-index: 100;color:#ffffff;
}
.chat-right-icon{
right:25rpx;top: 20rpx;z-index: 100;color:#95ec69;
}
.chat-left-content-bg{
background-color: #ffffff;
}
.chat-right-content-bg{
background-color: #95ec69;
}
</style>
- 页面
/pages/chat/chat.nvue
<template>
<view>
<!-- 导航栏 -->
<chat-navbar title="聊天" :fixed="true"
:showPlus="false" :showUser="false"
:showBack="true" navbarClass="bg-light"
:h5WeiXinNeedNavbar="h5WeiXinNeedNavbar">
<chat-navbar-icon-button slot="right"
@click="openMore" >
<text class="iconfont font-lg"></text>
</chat-navbar-icon-button>
</chat-navbar>
<!-- 聊天内容区域 -->
<scroll-view scroll-y class="bg-light position-fixed left-0 right-0"
:style="chatContentStyle" :show-scrollbar="false" @scroll="onScroll"
:scroll-into-view="scrollIntoViewId" >
<!-- 对话部分 -->
<view v-for="(item,index) in chatDataList" :key="index"
:id="'chat-item-'+index">
<chat-item :item="item" :index="index"
:prevTime="index>0 ? chatDataList[index-1].chat_time : 0"
ref="chatItem" @previewImages="previewImages"></chat-item>
</view>
</scroll-view>
<!-- 针对我们的app端点击聊天区域授权加号扩展菜单 -->
<!-- #ifdef APP -->
<view v-if="sendMessageMode == 'plus' || sendMessageMode == 'icon'"
class="position-fixed left-0 right-0"
:style="chatContentStyle"
@click="scrollViewClick"></view>
<!-- #endif -->
<!-- 底部聊天输入区域 --><!-- 修改:添加ref获取textarea实例 -->
<view class="position-fixed bottom-0 border-top
flex flex-row align-center justify-between"
style="background-color: #f7f7f7;width: 750rpx;
min-height: 90rpx;max-height: 320rpx;
padding-top: 12rpx;"
:style="chatBottomStyle">
<view class="flex align-center">
<chat-navbar-icon-button>
<text class="iconfont font-lg"></text>
</chat-navbar-icon-button>
<view class="flex align-center font-sm
bg-white px-2 py-1 border rounded">
<textarea ref="textarea" fixed auto-height :maxlength="-1"
style="width: 440rpx;min-height: 60rpx;
max-height: 274rpx;overflow-y: scroll;
text-align: justify;"
:adjust-position="false"
v-model="messageValue"
@focus="textareaFocus"
@input="onTextareaInput"
@blur="onTextareaBlur" ><!-- 新增:监听失焦事件 --><!-- 新增:监听输入事件 -->
</textarea>
</view>
</view>
<view class="flex align-center">
<chat-navbar-icon-button v-if="!messageValue"
@click="openIcon">
<text class="iconfont font-lg"></text>
</chat-navbar-icon-button>
<chat-navbar-icon-button v-if="!messageValue"
@click="openPlus">
<text class="iconfont font-lg"></text>
</chat-navbar-icon-button>
<view v-if="messageValue"
class="rounded bg-success px-2 py-1 mr-4"
hover-class="bg-hover-success"
@click="sendMessage('text')">
<text class="font text-white">发送</text>
</view>
</view>
</view>
<!-- 弹出菜单 --><!-- 主要修改区域 -->
<chat-tooltip ref="tooltipPlus" :mask="chatTooltipMask"
:maskTransparent="true" :isBottom="true"
:tooltipWidth="750"
:tooltipHeight="tooltipHeight"
transformOrigin = "center bottom"
tooltipClass ="bg-light border-0 rounded-0"
@hideTooltip="hideTooltip">
<view class="border-top border-light-secondary">
<!-- 表情菜单 -->
<swiper v-if="sendMessageMode === 'icon'"
:indicator-dots="groupedIconMenus.length > 1"
:duration="1000"
:style="tooltipPlusMenuStyle"
@change="handleSwiperChange"><!-- 添加分页切换事件 -->
<!-- 第一页:emoji表情(滚动显示) -->
<swiper-item v-if="emojiPageItems.length > 0">
<scroll-view scroll-y style="height: 100%;">
<view class="flex flex-row flex-wrap justify-start">
<view v-for="(item,itemIndex) in emojiPageItems"
:key="itemIndex"
class="flex flex-column justify-center align-center"
style="width: 12.5%; height: 120rpx; padding: 10rpx;"
@click="insertEmoji(item)">
<text style="font-size: 50rpx;">{{item.icon}}</text>
</view>
</view>
</scroll-view>
</swiper-item>
<!-- 其他类型表情分页显示 -->
<swiper-item v-for="(page,pageIndex) in otherPages"
:key="pageIndex">
<view class="flex flex-row flex-wrap justify-start">
<view v-for="(item,itemIndex) in page"
:key="pageIndex+itemIndex"
class="col-3 flex flex-column justify-center align-center"
style="height: 260rpx;"
@click="item ? swiperItemClick(item,itemIndex) : null"
><!-- 小程序添加空值检查 -->
<view class="bg-white rounded-lg flex flex-row
align-center justify-center mb-2"
style="width:120rpx;height: 120rpx;">
<u--image v-if="item.iconType == 'image'"
:src="item.icon" mode="aspectFit"
width="120rpx" height="120rpx" radius="0rpx"></u--image>
<text v-if="item.iconType == 'emoji'"
style="font-size: 40px;color: #222222;">{{item.icon}}</text>
<text v-if="item.iconType == 'custom'"
class="iconfont"
style="font-size: 26px;color: #222222;">{{item.icon}}</text>
<u-icon v-if="item.iconType == 'uview'"
:name="item.icon" color="#222222" size="26"></u-icon>
</view>
<text class="font-sm text-light-muted">{{item.name}}</text>
</view>
</view>
</swiper-item>
</swiper>
<!-- 加号菜单(保持不变) -->
<swiper v-else-if="sendMessageMode === 'plus'"
:indicator-dots="pageCount > 1" :duration="1000"
:style="tooltipPlusMenuStyle">
<swiper-item v-for="(page,index) in groupedPlusMenus" :key="index">
<view class="flex flex-row justify-start flex-wrap"
:style="swiperItemStyle">
<view class="col-3 flex flex-column justify-center align-center"
style="height: 260rpx;"
v-for="(item,itemIndex) in page" :key="itemIndex"
@click="swiperItemClick(item,itemIndex)">
<view class="bg-white rounded-lg
flex flex-row align-center justify-center mb-2"
style="width:120rpx;height: 120rpx;">
<u--image v-if="item.iconType == 'image'"
:src="item.icon" mode="aspectFit"
width="120rpx" height="120rpx" radius="0rpx"></u--image>
<text v-if="item.iconType == 'emoji'"
style="font-size: 40px;color: #222222;">{{item.icon}}</text>
<text v-if="item.iconType == 'custom'"
class="iconfont"
style="font-size: 26px;color: #222222;">{{item.icon}}</text>
<u-icon v-if="item.iconType == 'uview'"
:name="item.icon" color="#222222" size="26"></u-icon>
</view>
<text class="font-sm text-light-muted">{{item.name}}</text>
</view>
</view>
</swiper-item>
</swiper>
</view>
</chat-tooltip>
</view>
</template>
<script>
import toolJs from '@/common/mixins/tool.js';
import UniPermission from '@/common/mixins/uni_permission.js';
export default {
mixins:[toolJs],
data() {
return {
cursorPos: 0, // 新增:记录textarea光标位置
h5WeiXinNeedNavbar:false, // h5端微信上是否需要导航栏
statusBarHeight:0,//状态栏高度动态计算
fixedHeight:0, //占位:状态栏+导航栏
bottomSafeAreaHeight:0, // 底部安全距离
KeyboardHeight:0, //键盘高度
scrollIntoViewId:'', // 滚动到指定的元素id
messageValue:'', // 发送的内容信息
tooltipHeight:600, // 加号弹出菜单的高度rpx
sendMessageMode:"text",//发送消息的情况:文字|语音|加号|表情
// #ifdef MP || H5
chatTooltipMask:true,
// #endif
// #ifdef APP
chatTooltipMask:false,
// #endif
iconMenus:[
{ name:"微笑", icon:"/static/tabbar/index.png",
iconType:"image", eventType:"smile" },
{ name:"嘿嘿", icon:"😀",
iconType:"emoji", eventType:"heihei" },
{ name: "嗯,哼", icon: "https://docs-51yrc-com.oss-cn-hangzhou.aliyuncs.com/chat/iconMenus/en.gif", iconType: "image", eventType: "enheng" },
{ name:"嘻嘻", icon:"😁",
iconType:"emoji", eventType:"xixi" },
{ name:"笑哭了", icon:"😂",
iconType:"emoji", eventType:"xiaokule" },
{ name:"哈哈", icon:"😃",
iconType:"emoji", eventType:"haha" },
{ name:"大笑", icon:"😄",
iconType:"emoji", eventType:"daxiao" },
{ name:"苦笑", icon:"😅",
iconType:"emoji", eventType:"kuxiao" },
{ name:"斜眼笑", icon:"😆",
iconType:"emoji", eventType:"xieyanxiao" },
{ name:"微笑天使", icon:"😇",
iconType:"emoji", eventType:"weixiaotianshi" },
{ name:"眨眼", icon:"😉",
iconType:"emoji", eventType:"zhayan" },
{ name:"羞涩微笑", icon:"😊",
iconType:"emoji", eventType:"xiuseweixiao" },
{ name:"呵呵", icon:"🙂",
iconType:"emoji", eventType:"hehe" },
{ name:"倒脸", icon:"🙃",
iconType:"emoji", eventType:"daolian" },
{ name:"笑得满地打滚", icon:"🤣",
iconType:"emoji", eventType:"xiaodemandidagun" },
],
plusMenus:[ // 加号扩展菜单栏目
{ name:"照片", icon:"photo", iconType:"uview", eventType:"photo" },
{ name:"位置", icon:"map", iconType:"uview", eventType:"map" },
{ name:"拍摄", icon:"\ue62c", iconType:"custom", eventType:"camera" },
{ name:"我的名片", icon:"\ue69d", iconType:"custom", eventType:"mingpian" },
{ name:"视频", icon:"\ue66d", iconType:"custom", eventType:"video" },
// { name:"拍摄", icon:"\ue62c", iconType:"custom", eventType:"camera" },
// { name:"我的名片", icon:"\ue69d", iconType:"custom", eventType:"mingpian" },
// { name:"视频", icon:"\ue66d", iconType:"custom", eventType:"video" },
// { name:"拍摄", icon:"\ue62c", iconType:"custom", eventType:"camera" },
// { name:"我的名片", icon:"\ue69d", iconType:"custom", eventType:"mingpian" },
// { name:"视频", icon:"\ue66d", iconType:"custom", eventType:"video" },
],
chatDataList:[
{
avatar: 'https://docs-51yrc-com.oss-cn-hangzhou.aliyuncs.com/chat/avatar-06.png',
nickname: '彦祖',
chat_time: 1750148439,
data: '老师你好,我想咨询一下本季课程,如果我不学习上一个季度,可以直接学习本季度吗?',
user_id: 1,
type:'text', //image,video
isremove:false,
},
{
avatar: 'https://docs-51yrc-com.oss-cn-hangzhou.aliyuncs.com/chat/avatar-07.png',
nickname: '小二哥',
chat_time: 1750148449,
data: '同学你好,如果不学习上一个季度课程,如果你有vue的基础和js的基础知识,也可以学习本季度课程',
user_id: 2,
type:'text', //image,video
isremove:false,
},
{
avatar: 'https://docs-51yrc-com.oss-cn-hangzhou.aliyuncs.com/chat/avatar-06.png',
nickname: '彦祖',
chat_time: 1750148759,
data: '好的,我了解了,谢谢老师',
user_id: 1,
type:'text', //image,video
isremove:false,
},
{
avatar: 'https://docs-51yrc-com.oss-cn-hangzhou.aliyuncs.com/chat/avatar-07.png',
nickname: '小二哥',
chat_time: 1750148859,
data: '不用谢',
user_id: 2,
type:'text', //image,video
isremove:false,
},
{
avatar: 'https://docs-51yrc-com.oss-cn-hangzhou.aliyuncs.com/chat/avatar-06.png',
nickname: '彦祖',
chat_time: 1750148879,
data: 'ok',
user_id: 1,
type:'text', //image,video
isremove:false,
},
{
avatar: 'https://docs-51yrc-com.oss-cn-hangzhou.aliyuncs.com/chat/avatar-06.png',
nickname: '彦祖',
chat_time: 1750148879,
data: '哈哈哈',
user_id: 1,
type:'text', //image,video
isremove:false,
},
{
avatar: 'https://docs-51yrc-com.oss-cn-hangzhou.aliyuncs.com/chat/avatar-06.png',
nickname: '彦祖',
chat_time: 1750148879,
data: '嗯啦',
user_id: 1,
type:'text', //image,video
isremove:false,
},
],
}
},
mounted() {
let info = uni.getSystemInfoSync();
this.statusBarHeight = info.statusBarHeight;
this.fixedHeight = this.statusBarHeight + uni.upx2px(90);
this.bottomSafeAreaHeight = info.safeAreaInsets.bottom;
// 监听键盘高度变化
uni.onKeyboardHeightChange(res=>{
console.log('键盘高度变化',res);
// #ifdef H5 || MP
this.KeyboardHeight = res.height;
// #endif
// #ifdef APP
console.log('此时的输入模式', this.sendMessageMode);
if(this.sendMessageMode != 'plus' && this.sendMessageMode != 'icon'){
this.KeyboardHeight = res.height;
}
// #endif
if(this.KeyboardHeight){
this.chatContentToBottom();
}
});
// 页面加载完了之后就应该滚动到底部
this.$nextTick(()=>{
this.chatContentToBottom();
});
},
computed:{
chatContentStyle(){
let pbottom = this.bottomSafeAreaHeight == 0 ?
uni.upx2px(12) : this.bottomSafeAreaHeight;
let bottom = pbottom + uni.upx2px(90 + 12) + this.KeyboardHeight;
//如果是h5端用微信打开并且不需要导航栏的时候
if(this.isWeixinBrowser() && !this.h5WeiXinNeedNavbar){
this.fixedHeight = this.statusBarHeight + 0;
uni.setNavigationBarTitle({
title:'阿祖'
});
}
// #ifdef APP || MP
if(this.KeyboardHeight){
bottom = uni.upx2px(90 + 12 + 12) + this.KeyboardHeight;
}
// #endif
return `top:${this.fixedHeight}px;bottom:${bottom}px;`;
},
chatBottomStyle(){
let pbottom = this.bottomSafeAreaHeight == 0 ?
uni.upx2px(12) : this.bottomSafeAreaHeight;
// #ifdef APP || MP
if(this.KeyboardHeight){
pbottom = uni.upx2px(12);
}
// #endif
return `padding-bottom: ${pbottom}px;bottom:${this.KeyboardHeight}px;`;
},
//加号菜单每页的滑动样式
tooltipPlusMenuStyle(){
let pbottom = 0;
let height = uni.upx2px(this.tooltipHeight - 1) - pbottom;
// #ifdef APP || MP
pbottom = this.bottomSafeAreaHeight;
// #endif
return `padding-bottom:${pbottom}px;height:${height}px;`;
},
//加号菜单每页的布局样式
swiperItemStyle(){
let pbottom = 0;
let height = uni.upx2px(this.tooltipHeight - 1) - pbottom;
return `padding-bottom:${pbottom}px;height:${height}px;`;
},
// 加号菜单分页
// groupedPlusMenus(){
// const perPage = 8; // 每页8个
// const result = [];
// // 将数组plusMenus或者iconMenus每页8个分组
// for(let i=0;i<this.tooltipPlusMenusOrIconMenus.length; i += perPage){
// result.push(this.tooltipPlusMenusOrIconMenus.slice(i, i + perPage))
// }
// return result;
// },
//计算总页数
// pageCount(){
// return Math.ceil(this.tooltipPlusMenusOrIconMenus.length / 8);
// },
// 扩展菜单或者表情包数据源
tooltipPlusMenusOrIconMenus(){
if(this.sendMessageMode == 'plus' || this.sendMessageMode == 'icon'){
return this[`${this.sendMessageMode}Menus`]
}
return [];
},
// 修改:加号菜单分页计算
groupedPlusMenus() {
const perPage = 8; // 每页8个(2行)
const result = [];
for (let i = 0; i < this.plusMenus.length; i += perPage) {
result.push(this.plusMenus.slice(i, i + perPage));
}
return result;
},
// 修改:计算总页数(分别处理两种菜单)
pageCount() {
if (this.sendMessageMode === 'plus') {
return Math.ceil(this.plusMenus.length / 8);
} else if (this.sendMessageMode === 'icon') {
return this.groupedIconMenus.length;
}
return 0;
},
// 新增:表情菜单计算属性
emojiList() {
return this.iconMenus.filter(item => item.iconType === 'emoji');
},
otherList() {
return this.iconMenus.filter(item => item.iconType !== 'emoji');
},
emojiPageItems() {
return this.emojiList; // 所有emoji表情放在第一页
},
otherPages() {
const perPage = 8; // 每页8个(2行)
const pages = [];
for (let i = 0; i < this.otherList.length; i += perPage) {
pages.push(this.otherList.slice(i, i + perPage));
}
return pages;
},
groupedIconMenus() {
// 总页数 = 1 (emoji页) + 其他类型页数
const pages = [];
if (this.emojiPageItems.length > 0) {
pages.push(this.emojiPageItems); // 第一页放emoji
}
return pages.concat(this.otherPages);
},
// 多图预览图片地址的数组集合
previewImagesList(){
let arr = [];
this.chatDataList.forEach(item=>{
if(item.type == 'image' || (item.type == 'iconMenus' &&
item.dataType && item.dataType == 'image')){
arr.push(item.data);
}
});
return arr;
},
},
methods: {
// 新增:textarea输入事件记录光标位置
onTextareaInput(e) {
// #ifdef H5 || APP
this.cursorPos = e.detail.cursor;
// #endif
},
// 新增:textarea失焦事件记录光标位置
onTextareaBlur(e) {
this.cursorPos = e.detail.cursor || this.messageValue.length;
},
// 新增:插入表情到textarea
insertEmoji(item) {
if (!item || !item.icon) return;
const emoji = item.icon;
const text = this.messageValue || '';
// 插入到当前光标位置
const newText = text.substring(0, this.cursorPos) +
emoji +
text.substring(this.cursorPos);
this.messageValue = newText;
// 更新光标位置(在插入的表情后面)
const newCursorPos = this.cursorPos + emoji.length;
this.cursorPos = newCursorPos;
// 设置光标位置(H5/APP支持)
this.$nextTick(() => {
if (!this.$refs.textarea) return;
let textarea;
// 处理 H5 平台的特殊情况
// #ifdef H5
textarea = this.$refs.textarea.$el; // 获取原生 DOM 元素
// #endif
// #ifndef H5
textarea = this.$refs.textarea;
// #endif
if (textarea) {
// 尝试设置光标位置
if (typeof textarea.setSelectionRange === 'function') {
try {
textarea.setSelectionRange(newCursorPos, newCursorPos);
} catch (e) {
console.warn('设置光标位置失败', e);
}
}
// 确保输入框聚焦
if (typeof textarea.focus === 'function') {
try {
textarea.focus();
} catch (e) {
console.warn('聚焦输入框失败', e);
}
}
}
});
},
//点击加号扩展菜单的某一项
// swiperItemClick(item,itemIndex){
// if(this.sendMessageMode == 'icon'){
// console.log('点击了表情包里面的某个表情');
// // this.messageValue += `[${item.name}]`;
// this.sendMessage('iconMenus',item)
// }else{
// console.log('点击加号扩展菜单的某一项',item.eventType);
// switch (item.eventType){
// case 'phote':
// break;
// case 'map':
// break;
// case 'camera':
// break;
// case 'mingpian':
// break;
// case 'video':
// break;
// }
// }
// },
// 修改:点击菜单项处理
async swiperItemClick(item, itemIndex) {
console.log('点击菜单项处理',item);
if (!item) return; // 防止undefined错误
if (this.sendMessageMode === 'icon') {
if (item.iconType === 'emoji') {
this.insertEmoji(item); // emoji插入输入框
} else {
this.sendMessage('iconMenus', item); // 其他类型直接发送
}
} else {
console.log('点击加号扩展菜单的某一项',item.eventType);
switch (item.eventType){
case 'photo':
await this.handlePhoto();
break;
case 'map':
break;
case 'camera':
break;
case 'mingpian':
break;
case 'video':
break;
}
}
},
// 发图片
async handlePhoto(){
try{
const permission = new UniPermission();
const granted = await permission.requestPermission('photo',
'需要访问您的相册来选择图片','本功能需要您打开相册');
if(granted){
console.log('用户已授权开启相册,可以选择照片了');
this.chooseImage();
}else{
uni.showToast({
title: '您没有授权开启相册,无法发图片',
icon:'none',
duration:3000
});
}
}catch(error){
console.error('权限申请异常:' + error);
uni.showToast({
title:'权限申请失败:' + error.message,
icon:'none',
duration:3000
});
}
},
//选择照片发送
chooseImage(){
uni.chooseImage({
count:9,
//sizeType:['original','compressed'],
sourceType:['album'],
success: (res) => {
console.log('选择照片res',res);
if(res.tempFilePaths && res.tempFilePaths.length){
// 发送到服务器或者第三方云存储
// 页面效果渲染效果
//单张
//this.sendMessage('image',{path:res.tempFilePaths[0]});
// 多张
res.tempFilePaths.forEach(item=>{
this.sendMessage('image',{path:item});
});
}
},
fail: (err) => {
console.error('选择图片失败:', err);
let errorMsg = '选择图片失败';
if(err.errMsg.includes('permission')){
errorMsg = '相册访问权限不足';
}else if(err.errMsg.includes('cancel')){
return; // 用户不授权不提示
}
uni.showToast({
title:errorMsg,icon:'none',duration:3000
});
}
});
},
//预览多张图片
previewImages(e){
console.log('预览多张图片在页面',e);
uni.previewImage({
urls:this.previewImagesList,
current:e.item.data,
indicator:'default',
});
},
handleSwiperChange(e) {
console.log('分页切换', e.detail.current);
// 可以在这里处理分页切换逻辑
},
//点击聊天区域
scrollViewClick(){
// #ifdef APP
console.log('点击聊天区域');
this.KeyboardHeight = 0;
uni.hideKeyboard();
this.$refs.tooltipPlus.hide();
this.sendMessageMode = "text";
// #endif
},
// 文本输入框聚焦
textareaFocus(){
// #ifdef APP
this.sendMessageMode = "text";
// #endif
},
//点击笑脸图标
openIcon(){
console.log('点击了笑脸');
// #ifdef APP
this.sendMessageMode = "icon";
uni.hideKeyboard();
// #endif
// #ifdef H5 || MP
this.sendMessageMode = "icon";
// #endif
this.$refs.tooltipPlus.show();
// #ifdef APP || MP || H5
this.KeyboardHeight = uni.upx2px(this.tooltipHeight);
this.chatContentToBottom();
// #endif
},
//点击了加号
openPlus(){
console.log('点击了加号');
// #ifdef APP
this.sendMessageMode = "plus";
uni.hideKeyboard();
// #endif
// #ifdef H5 || MP
this.sendMessageMode = "plus";
// #endif
this.$refs.tooltipPlus.show();
// #ifdef APP || MP || H5
this.KeyboardHeight = uni.upx2px(this.tooltipHeight);
this.chatContentToBottom();
// #endif
},
// 弹出框隐藏了
hideTooltip(){
console.log('弹出框隐藏了');
// #ifdef APP || MP || H5
this.KeyboardHeight = 0;
this.chatContentToBottom();
// #endif
},
//发送消息
sendMessage(msgType, option = {}){
console.log('发送消息',msgType);
let msg = {
avatar: 'https://docs-51yrc-com.oss-cn-hangzhou.aliyuncs.com/chat/avatar-07.png',
nickname: '小二哥',
user_id: 2,
chat_time: (new Date()).getTime(),
data: '',
type:msgType, //image,video
isremove:false,
};
switch (msgType){
case 'text':
msg.data = this.messageValue;
break;
case 'iconMenus':
console.log('iconMenus的数据',option);
msg.data = option.icon;
msg.dataType = option.iconType;
break;
case 'image':
console.log('image的数据',option);
msg.data = option.path;
break;
}
this.chatDataList.push(msg);
// 清空发送的内容然后还要滚动到底部
if(msgType == 'text') this.messageValue = '';
this.chatContentToBottom();
},
openMore(){
console.log('点击了三个点图标');
},
//聊天内容滚到到底部
chatContentToBottom(){
// #ifdef APP
let chatItems = this.$refs.chatItem;
let lastIndex = chatItems.length - 1 == 0 ? 0 : chatItems.length - 1;
let last = chatItems[lastIndex];
const dom = weex.requireModule('dom');
dom.scrollToElement(last, {});
// #endif
// #ifdef MP || H5
if(this.chatDataList.length == 0) return;
const lastIndex = this.chatDataList.length - 1;
this.scrollIntoViewId = `chat-item-${lastIndex}`;
setTimeout(()=>{
this.scrollIntoViewId = '';
this.$nextTick(()=>{
this.scrollIntoViewId = `chat-item-${lastIndex}`;
});
},100)
// #endif
},
onScroll(){
console.log('页面发生了滚动');
}
},
watch:{
// 监听聊天记录数据变化,自动滚动到底部
chatDataList:{
handler(){
this.$nextTick(()=>{
this.chatContentToBottom();
});
},
deep:true
},
sendMessageMode(newVal,oldVal){
// #ifdef APP
console.log('监听发送模式',newVal);
if(newVal != 'plus' && newVal != 'icon'){
this.$refs.tooltipPlus.hide();
}
// #endif
},
},
}
</script>
<style>
/* #ifdef H5 */
@import '/common/css/common.nvue.vue.css';
/* #endif */
</style>
# 四、加号扩展菜单功能
内容过多,在新页面打开,具体查看: