uni-app+vue仿微信聊天APP界面|uniapp仿微信朋友圈

基于uniapp+vue仿微信聊天室uniapp-chatroom项目,vue语法及类似小程序api开发原生APP应用,实现了发送图文消息、表情(gif动图),图片预览、地图位置、红包、仿微信朋友圈等功能。

H5 / 小程序 / App端测试效果如下 (后续大图统一展示App端)

技术实现

  • 编辑器:HBuilder X
  • 技术框架:uni-app + vue
  • 状态管理:Vuex
  • iconfont图标:阿里字体图标库
  • 自定义导航栏 + 底部Tabbar
  • 弹窗组件:uniPop(基于uni-app封装模态弹窗)
  • 测试环境:H5端 + 小程序 + App端(三端均兼容)
  • 高德地图:vue-amap

引入公共组件及样式main.js

import Vue from 'vue'
import App from './App'

// >>>引入css
import './assets/fonts/iconfont.css'
import './assets/css/reset.css'
import './assets/css/layout.css'

// >>>引入状态管理
import store from './store'
Vue.prototype.$store = store

// >>>引入公共组件
import headerBar from './components/header/header.vue'
import tabBar from './components/tabbar/tabbar.vue'
import popupWindow from './components/popupWindow.vue'
Vue.component('header-bar', headerBar)
Vue.component('tab-bar', tabBar)
Vue.component('popup-window', popupWindow)

// >>>引入uniPop弹窗组件
import uniPop from './components/uniPop/uniPop.vue'
Vue.component('uni-pop', uniPop)

Vue.config.productionTip = false
App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount()

uniapp+vuex状态管理实现登录验证

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        user: uni.getStorageSync('user'),
        token: uni.getStorageSync('token'),
    },
    mutations: {
        // 存储token
        SET_TOKEN(state, data) {
            state.token = data
            uni.setStorageSync('token', data)
        },
        // 存储用户名
        SET_USER(state, data) {
            state.user = data
            uni.setStorageSync('user', data)
        },
        ...
    },
})
<script>
    import { mapState, mapMutations } from 'vuex'
    import util from '../../utils/util.js'
    
    export default {
        data() {
            return {
                formObj: {},
            }
        },
        computed: {
            ...mapState(['user', 'token'])
        },
        mounted() {
            // 判断是否有登录
            if(this.user){
                uni.redirectTo({url: '/pages/index/index'})
            }
        },
        methods: {
            // 提交表单
            handleSubmit(e) {
                ...
            }
        }
    }
</script>
class Util {
	// 随机token
	static setToken(len) {
		len = len || 32
		let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
		let maxLen = $chars.length
		let pwd = ''
		for(var i = 0; i < len; i++){
			pwd += $chars.charAt(Math.floor(Math.random() * maxLen))
		}
		return pwd
	}
	
	// 验证手机号
	static checkTel(val) {
		let reg = 11 && /^((13|14|15|17|18)[0-9]{1}\d{8})$/
		if(val == '' || !reg.test(val)){
			return false
		}
		return true
	}
}

export default Util

uniapp仿微信朋友圈功能

如何实现微信朋友圈页面向下滚动,顶部导航栏由透明变背景色

通过onPageScroll函数实现自定义导航上下滑动自动调整导航栏的透明度,滑动到距离顶部200 效果如下图二

/**
 * @tpl 朋友圈模板
 */

<template>
    <view class="flexbox flex_col">
        <header-bar :isBack="true" title="朋友圈" :bgColor="{background: headerBarBackground}" transparent>
            <text slot="back" class="uni_btnIco iconfont icon-arrL"></text>
            <text slot="iconfont" class="uni_btnIco iconfont icon-publish mr_5" @tap="handlePublish"></text>
        </header-bar>
        
        <view class="uni__scrollview flex1">
            <view class="uni-friendZone">
                ...
            </view>
        </view>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                headerBarBackground: 'transparent'
            }
        },
        onPageScroll : function(e) {
            // console.log("滚动距离为:" + e.scrollTop);
            this.headerBarBackground = 'rgba(65,168,99,'+e.scrollTop / 200+')'
        },
        methods: {
            ...
        }
    }
</script>

<style scoped>

</style>

聊天部分代码片段

<script>
    const emotionJson = require('./mock-emotion.js')
    const messageJson = require('./mock-chat.js')
    
    export default {
        data() {
            return {
                scrollTop: 0,
                
                showFootToolbar: false,
                showEmotionChoose: false,
                
                editorText: '',
                editorLastCursor: null,
                
                // 表情json
                emotionList: emotionJson,
                
                // 消息记录
                messageList: messageJson,
                
                // 预览图片临时数组
                previewImgArray: [],
            }
        },
        mounted() {
            this.scrollToBottom()
        },
        updated() {
            this.scrollToBottom()
        },
        methods: {
            // 滚动至聊天底部
            scrollToBottom(t) {
                let that = this
                let query = uni.createSelectorQuery()
                query.select('#scrollview').boundingClientRect()
                query.select('#msglistview').boundingClientRect()
                query.exec((res) => {
                    // console.log(res)
                    if(res[1].height > res[0].height){
                        that.scrollTop = res[1].height - res[0].height
                    }
                })
            },
            
            // 点击聊天消息区域
            msgPanelTaped() {
                if(!this.showFootToolbar) return
                this.showFootToolbar = false
            },
            
            // 表情、选择区切换
            swtEmotionChooseView(bool) {
                this.showFootToolbar = true
                this.showEmotionChoose = bool
            },
            
            ...
            
            // 点击表情
            handleEmotionTaped(emoj) {
                if(emoj == 'del') return
                // 在光标处插入表情
                let startStr = this.editorText.substr(0, this.editorLastCursor)
                let endStr = this.editorText.substr(this.editorLastCursor)
                this.editorText = startStr + `${emoj}` + endStr
            },
            
            
            // >>> 【选择区功能模块】------------------------------------------
            // 选择图片
            handleLaunchImage() {
                let that = this
                let msglist = this.messageList
                let len = msglist.length
                // 消息队列
                let data = {
                    id: `msg${++len}`,
                    msgtype: 5,
                    isme: true,
                    avator: '/static/uimg/u__chat_img1.jpg',
                    author: 'King',
                    msg: '',
                    imgsrc: '',
                    videosrc: ''
                }
                
                uni.chooseImage({
                    count: 1,
                    sourceType: ['album'],
                    success: function(res){
                        // console.log(res)
                        // console.log(res.tempFilePaths)
                        data.imgsrc = res.tempFilePaths.toString()
                        msglist = msglist.concat(data)
                        that.messageList = msglist
                    }
                })
            },
            
            ...
            
            // 位置
            handleChooseLocation() {
                let that = this
                let msglist = this.messageList
                let len = msglist.length
                // 消息队列
                let data = {
                    id: `msg${++len}`,
                    msgtype: 8,
                    isme: true,
                    avator: '/static/uimg/u__chat_img1.jpg',
                    author: 'King',
                    msg: '',
                    imgsrc: '',
                    videosrc: ''
                }
                
                uni.chooseLocation({
                    success: (res) => {
                        console.log(res)
                        // 插入消息
                        data.msg = {
                            name: res.name,
                            address: res.address,
                            latitude: res.latitude,
                            longitude: res.longitude
                        }
                        msglist = msglist.concat(data)
                        that.messageList = msglist
                    }
                })
            },
            
        }
    }
</script>

好了,今天的分享就到这里,后续会继续分享一些项目实例,希望大家能喜欢💪💪~~

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

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

编辑于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券