优秀的编程知识分享平台

网站首页 > 技术文章 正文

Vue3.0+Vant3聊天室|vue3仿微信App聊天实例

nanyue 2024-09-02 19:10:30 技术文章 7 ℃

最近一直在捣鼓Vue3开发,不得不说Vue.js越来越优秀了。尤大推出的Vite构建工具真是极速,本来是想着使用vite构建vue3项目,不知道为啥vite构建的项目使用vant-ui3.0会报错,不知道大家有没有遇到过这种情况。后来就改用vue/cli来构建vue3项目了。

vue3更加灵活、高效,目前拥有star高达20K+

https://v3.cn.vuejs.org/
https://github.com/vuejs/vue-next

项目简介

vue3-chatroom 基于vue3.0+vuex+vue-router4+vant3.0+v3popup等技术开发的手机端仿微信App界面聊天项目。实现了发送消息/动图、图片/视频预览、网址链接预览、消息下拉、红包/朋友圈等功能。

使用技术

  • 技术框架:vue3.0+vuex4+vue-router4
  • UI组件库:vant-ui3.0(有赞Vue3移动端组件库)
  • 弹框组件:V3Popup(基于Vue3自定义移动端弹框)
  • 字体图标:阿里iconfont字体图标库

效果预览

Vue3自定义Navbar和tabBar组件

项目中顶部导航及底部Tabbar组件都是自定义实现。分别封装在compoents目录下。

前段时间有分享过一篇文章,这里就不详细介绍了。大家如果感兴趣可以去看看。

Vue3.0自定义导航栏+底部tabbar组件

Vue3自定义弹框v3popup

项目中所有弹框功能都是v3popup组件实现。

大家如果对弹框功能感兴趣,可以看看下面这个演示视频。

https://www.ixigua.com/i6911339156538917388/

vue.config.js配置

vue3中项目的一些常用简单配置。

/**
 * Vue3页面配置文件
 */

const path = require('path')

module.exports = {
    // 基本路径
    // publicPath: '/',

    // 输出文件目录
    // outputDir: 'dist',

    // assetsDir: '',

    // 环境配置
    devServer: {
        // host: 'localhost',
        // port: 8080,
        // 是否开启https
        https: false,
        // 编译完是否打开网页
        open: false,
        
        // 代理配置
        // proxy: {
        //     '^/api': {
        //         target: '<url>',
        //         ws: true,
        //         changeOrigin: true
        //     },
        //     '^/foo': {
        //         target: '<other_url>'
        //     }
        // }
    },

    // webpack配置
    chainWebpack: config => {
        // 配置路径别名
        config.resolve.alias
            .set('@', path.join(__dirname, 'src'))
            .set('@assets', path.join(__dirname, 'src/assets'))
            .set('@components', path.join(__dirname, 'src/components'))
            .set('@views', path.join(__dirname, 'src/views'))
    }
}

入口main.js配置

引入vuex状态管理、路由及一些公共组件。

/**
 * 主入口页面js
 */

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

// 引入vuex和地址路由
import store from './store'
import router from './router'

// 引入js
import '@assets/js/fontSize'

// 引入公共组件
import Plugins from './plugins'

const app = createApp(App)

app.use(store)
app.use(router)
app.use(Plugins)

app.mount('#app')

Vue3路由配置

/**
 * Vue3.0路由地址
 */

import { createRouter, createWebHistory } from 'vue-router'

const routes = [
    // 登录/注册
    {
        name: 'login', path: '/login',
        component: () => import('../views/auth/login.vue'),
    },
    {
        name: 'register', path: '/register',
        component: () => import('../views/auth/register.vue'),
    },

    // 首页
    {
        name: 'index', path: '/',
        component: () => import('../views/index'),
        meta: { requireAuth: true }
    },

    // ...
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})

export default router

vue3中实现全局钩子拦截状态。

// 全局钩子拦截登录状态
router.beforeEach((to, from, next) => {
    const token = store.state.token

    // 判断当前路由地址是否需要登录权限
    if(to.meta.requireAuth) {
        if(token) {
            next()
        }else {
            // 未登录授权
            V3Popup({
                content: '还未登录授权!', position: 'top', time: 2,
                onEnd: () => {
                    next({ path: '/login' })
                }
            })
        }
    }else {
        next()
    }
})

Vue3登录表单实现

vue3.0中实现表单登录验证功能。

<!-- //登录模板 -->
<template>
    <div>
        <div class="vui__scrollview vui__scrollview-lgreg flex1">
            <div class="nt__lgregPanel">
				<div class="lgreg-header">
					<div class="slogan">
						<img class="logo" src="@assets/v3-logo.png" />
						<p class="text ff-st">欢迎使用Vue3-Chatroom</p>
					</div>
					<div class="forms">
						<form @submit.prevent="handleSubmit">
							<div class="item flexbox flex_alignc">
								<input class="iptxt flex1" type="text" v-model="formObj.tel" placeholder="请输入手机号" maxlength="11" />
							</div>
							<div class="item flexbox flex_alignc">
								<input class="iptxt flex1" type="password" v-model="formObj.pwd" placeholder="请输入密码" />
							</div>
							<div class="item btns">
								<button class="vui__btn vui__btn-primary" type="submit">登录</button>
							</div>
							<div class="item lgreg-lk">
								<router-link class="navigator" to="#">忘记密码</router-link>
								<router-link class="navigator" to="/register">注册账号</router-link>
							</div>
						</form>
					</div>
				</div>
			</div>
        </div>
    </div>
</template>

<script>
import { reactive, inject, getCurrentInstance } from 'vue'
export default {
    components: {},
    setup() {
        const { ctx } = getCurrentInstance()

        const v3popup = inject('v3popup')

        const utils = inject('utils')

        const formObj = reactive({})

        const Snackbar = (content) => {
            v3popup({
                content: `<div style='text-align:left;'>${content}</div>`,
                popupStyle: 'background:#ff4848;border-radius:1px;color:#fff;',
                position: 'bottom',
                time: 2
            })
        }

        const handleSubmit = () => {
            if(!formObj.tel){
                Snackbar('手机号不能为空!')
            }else if(!utils.checkTel(formObj.tel)){
                Snackbar('手机号格式不正确!')
            }else if(!formObj.pwd){
                Snackbar('密码不能为空!')
            }else{
                ctx.$store.commit('SET_TOKEN', utils.setToken());
                ctx.$store.commit('SET_USER', formObj.tel);

                v3popup({
                    content: '恭喜,登录成功!', time: 2, shadeClose: false,
                    onEnd() {
                        ctx.$router.push('/')
                    }
                })
            }
        }

        return {
            formObj,
            handleSubmit
        }
    }
}
</script>

项目中所有的模板页及功能均是采用Vue3语法实现,全面拥抱Composition API语法。

ok,基于Vue3开发聊天功能,暂时就分享到这里。感谢大家的阅读~~

Tags:

最近发表
标签列表