前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >uniapp-vue3-wechat聊天实例|uni-app+pinia2仿微信app

uniapp-vue3-wechat聊天实例|uni-app+pinia2仿微信app

原创
作者头像
andy2018
修改2024-04-29 22:02:12
1460
修改2024-04-29 22:02:12

Uniapp_Vue3_Chat基于uni-app+vue3+pinia2+uv-ui跨三端(h5+小程序+APP端)仿微信聊天。

uni-vue3-wchat项目采用vue3 setup语法编码,支持编译到H5+小程序+App端

技术栈

  • 编辑器:HbuilderX 4.0.8
  • 技术框架:Uniapp+Vue3+Pinia2+Vite4.x
  • 组件库:uni-ui+uv-ui
  • 弹窗组件:uv3-popup(uniapp+vue3多端自定义弹框组件)
  • 自定义组件:uv3-navbar+uv3-tabbar组件
  • 缓存服务:pinia-plugin-unistorage
  • 编译支持:H5+小程序+APP端

项目结构目录

main.js配置

代码语言:typescript
复制
/**
 * 入口文件 main.js
*/

import { createSSRApp } from 'vue'
import App from './App'

// 引入pinia状态管理
import pinia from '@/pinia'

export function createApp() {
    const app = createSSRApp(App)
    app.use(pinia)
    return {
        app,
        pinia
    }
}

入口模板App.vue采用vue3 setup语法编码。

代码语言:typescript
复制
// 入口模板 By Andy Q:282310962
<script setup>
    import { provide } from 'vue'
    import { onLaunch, onShow, onHide, onPageNotFound } from '@dcloudio/uni-app'
    
    onLaunch(() => {
        console.log('App Launch')
        
        uni.hideTabBar()
        loadSystemInfo()
    })
    
    onShow(() => {
        console.log('App Show')
    })
    
    onHide(() => {
        console.log('App Hide')
    })
    
    onPageNotFound((e) => {
        console.warn('Route Error:', `${e.path}`)
    })
    
    // 获取系统设备信息
    const loadSystemInfo = () => {
        uni.getSystemInfo({
            success: (e) => {
                // 获取手机状态栏高度
                let statusBar = e.statusBarHeight
                let customBar
                
                // #ifndef MP
                customBar = statusBar + (e.platform == 'android' ? 50 : 45)
                // #endif
                
                // #ifdef MP-WEIXIN
                // 获取胶囊按钮的布局位置信息
                let menu = wx.getMenuButtonBoundingClientRect()
                // 导航栏高度 = 胶囊下距离 + 胶囊上距离 - 状态栏高度
                customBar = menu.bottom + menu.top - statusBar
                // #endif
                
                // #ifdef MP-ALIPAY
                customBar = statusBar + e.titleBarHeight
                // #endif
                
                // 由于globalData在vue3 setup存在兼容性问题,改为provide/inject替代方案
                provide('globalData', {
                    statusBarH: statusBar,
                    customBarH: customBar,
                    screenWidth: e.screenWidth,
                    screenHeight: e.screenHeight,
                    platform: e.platform
                })
            }
        })
    }
</script>

<style>
    /* #ifndef APP-NVUE */
    @import 'static/fonts/iconfont.css';
    /* #endif */
</style>
<style lang="scss">
    @import 'styles/reset.scss';
    @import 'styles/layout.scss';
</style>

公共布局模板

项目结构采用顶部导航+主体内容区+底部区域三个模块。

代码语言:typescript
复制
<!-- 公共布局模板 -->

<!-- #ifdef MP-WEIXIN -->
<script>
    export default {
        /**
         * 解决小程序class、id透传问题
         * manifest.json中配置mergeVirtualHostAttributes: true, 在微信小程序平台不生效,组件外部传入的class没有挂到组件根节点上,在组件中增加options: { virtualHost: true }
         * https://github.com/dcloudio/uni-ui/issues/753
         */
        options: { virtualHost: true }
    }
</script>
<!-- #endif -->

<script setup>
    const props = defineProps({
        // 是否显示自定义tabbar
        showTabBar: { type: [Boolean, String], default: false },
    })
</script>

<template>
    <view class="uv3__container flexbox flex-col flex1">
        <!-- 顶部插槽 -->
        <slot name="header" />
        
        <!-- 内容区 -->
        <view class="uv3__scrollview flex1">
            <slot />
        </view>
        
        <!-- 底部插槽 -->
        <slot name="footer" />
        
        <!-- tabbar栏 -->
        <uv3-tabbar v-if="showTabBar" hideTabBar fixed />
    </view>
</template>

uni-app+vue3实现九宫格图像

代码语言:typescript
复制
<script setup>
    import { onMounted, ref, computed, watch, getCurrentInstance } from 'vue'
    
    const props = defineProps({
        // 图像组
        avatar: { type: Array, default: null },
    })
    
    const instance = getCurrentInstance()
    
    const uuid = computed(() => Math.floor(Math.random() * 10000))
    const avatarPainterId = ref('canvasid' + uuid.value)
    
    const createAvatar = () => {
        const ctx = uni.createCanvasContext(avatarPainterId.value, instance)
        // 计算图像在画布上的坐标
        const avatarSize = 12
        const gap = 2
        for(let i = 0, len = props.avatar.length; i < len; i++) {
            const row = Math.floor(i / 3)
            const col = i % 3
            const x = col * (avatarSize + gap)
            const y = row * (avatarSize + gap)
            
            ctx.drawImage(props.avatar[i], x, y, avatarSize, avatarSize)
        }
        ctx.draw(false, () => {
            // 输出临时图片
            /* uni.canvasToTempFilePath({
                canvasId: avatarPainterId.value,
                success: (res) => {
                    console.log(res.tempFilePath)
                }
            }) */
        })
    }
    
    onMounted(() => {
        createAvatar()
    })
    
    watch(() => props.avatar, () => {
        createAvatar()
    })
</script>

<template>
    <template v-if="avatar.length > 1">
        <view class="uv3__avatarPainter">
            <canvas :canvas-id="avatarPainterId" class="uv3__avatarPainter-canvas"></canvas>
        </view>
    </template>
    <template v-else>
        <image class="uv3__avatarOne" :src="avatar[0]" />
    </template>
</template>

<style lang="scss" scoped>
    .uv3__avatarPainter {background-color: #eee; border-radius: 5px; overflow: hidden; padding: 2px; height: 44px; width: 44px;}
    .uv3__avatarPainter-canvas {height: 100%; width: 100%;}
    .uv3__avatarOne {border-radius: 5px; height: 44px; width: 44px;}
</style>

uniapp+vue3自定义顶部导航+底部菜单栏

代码语言:typescript
复制
<uv3-navbar :back="true" title="标题内容" bgcolor="#07c160" color="#fff" fixed zIndex="1010" />

<uv3-navbar custom bgcolor="linear-gradient(to right, #07c160, #0000ff)" color="#fff" center transparent zIndex="2024">
    <template #back><uni-icons type="close" /></template>
    <template #backText><text>首页</text></template>
    <template #title>
        <image src="/static/logo.jpg" style="height:20px;width:20px;" /> Admin
    </template>
    <template #right>
        <view class="ml-20" @click="handleAdd"><text class="iconfont icon-tianjia"></text></view>
        <view class="ml-20"><text class="iconfont icon-msg"></text></view>
    </template>
</uv3-navbar>

uniapp+vue3聊天功能

目前该增强版输入框已经免费发布到插件市场,有需要的可以去下载使用。

https://ext.dcloud.net.cn/plugin?id=13275

代码语言:typescript
复制
<!-- 按住说话模板 -->
<view v-if="voicePanelEnable" class="uv3__voicepanel-popup">
    <view class="uv3__voicepanel-body flexbox flex-col">
        <!-- 取消发送+语音转文字 -->
        <view v-if="!voiceToTransfer" class="uv3__voicepanel-transfer">
            <!-- 提示动效 -->
            <view class="animtips flexbox" :class="voiceType == 2 ? 'left' : voiceType == 3 ? 'right' : null"><Waves :lines="[2, 3].includes(voiceType) ? 10 : 20" /></view>
            <!-- 操作项 -->
            <view class="icobtns flexbox">
                <view class="vbtn cancel flexbox flex-col" :class="{'hover': voiceType == 2}" @click="handleVoiceCancel"><text class="vicon uv3-icon uv3-icon-close"></text></view>
                <view class="vbtn word flexbox flex-col" :class="{'hover': voiceType == 3}"><text class="vicon uv3-icon uv3-icon-word"></text></view>
            </view>
        </view>
        
        <!-- 语音转文字 -->
        <view v-if="voiceToTransfer" class="uv3__voicepanel-transfer result fail">
            <!-- 提示动效 -->
            <view class="animtips flexbox"><uni-icons type="info-filled" color="#fff" size="20"></uni-icons><text class="c-fff">未识别到文字</text></view>
            <view class="icobtns flexbox">
                <view class="vbtn cancel flexbox flex-col" @click="handleVoiceCancel"><text class="vicon uv3-icon uv3-icon-chexiao"></text>取消</view>
                <view class="vbtn word flexbox flex-col"><text class="vicon uv3-icon uv3-icon-audio"></text>发送原语音</view>
                <view class="vbtn check flexbox flex-col"><text class="vicon uv3-icon uv3-icon-duigou"></text></view>
            </view>
        </view>
        
        <!-- 背景语音图 -->
        <view class="uv3__voicepanel-cover">
            <image v-if="!voiceToTransfer" src="/static/voice_bg.webp" :webp="true" mode="widthFix" style="width: 100%;" />
        </view>
        <!-- // 提示文字 -->
        <view v-if="!voiceToTransfer" class="uv3__voicepanel-tooltip">{{voiceTypeMap[voiceType]}}</view>
        <!-- 背景图标 -->
        <view v-if="!voiceToTransfer" class="uv3__voicepanel-fixico"><text class="uv3-icon uv3-icon-audio fs-50"></text></view>
    </view>
</view>

代码语言:typescript
复制
// 触摸事件(开始/更新/结束)
const handleTouchStart = (e) => {
	// console.log(e)
	voiceType.value = 1
	voicePanelEnable.value = true
}
const handleTouchUpdate = (e) => {
	// console.log(e)
	let touches = e.touches[0]
	let swipeY = globalData.screenHeight - 150;
	let swipeX = globalData.screenWidth / 2 + 50;
	if(touches.clientY >= swipeY) {
		voiceType.value = 1 // 松开发送
	}else if(touches.clientY < swipeY && touches.clientX < swipeX) {
		voiceType.value = 2 // 左滑松开取消
	}else if(touches.clientY < swipeY && touches.clientX >= swipeX) {
		voiceType.value = 3 // 右滑语音转文字
	}
}

https://cloud.tencent.com/developer/article/2400555

https://cloud.tencent.com/developer/article/2393406

Okey,综上就是uniapp+vue3+uni-ui实战开发微信app聊天的一些知识分享,希望对大家有所帮助!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 技术栈
  • 项目结构目录
  • main.js配置
  • 公共布局模板
  • uni-app+vue3实现九宫格图像
  • uniapp+vue3自定义顶部导航+底部菜单栏
  • uniapp+vue3聊天功能
相关产品与服务
云开发 CloudBase
云开发(Tencent CloudBase,TCB)是腾讯云提供的云原生一体化开发环境和工具平台,为200万+企业和开发者提供高可用、自动弹性扩缩的后端云服务,可用于云端一体化开发多种端应用(小程序、公众号、Web 应用等),避免了应用开发过程中繁琐的服务器搭建及运维,开发者可以专注于业务逻辑的实现,开发门槛更低,效率更高。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档