介绍:前台使用vue开发的单页面,后台使用ant design pro单页面,实现手机端和后台聊天功能。
效果如图(PC+移动):
一、申请融云账号(token、appKey)
建议先看教程:sdk使用介绍
过一遍教程,接下来开始写
二、引入融云IM
如图:
位置:public/index.html,引入
三、可以正常使用RongIMLib其自带方法了
app.vue 不是全代码(因为只是连接)
created () { //生命周期函数-可发起求 let that = this //融云初始化 RongIMLib.RongIMClient.init('4z3hrv4ovrt'); //------------------------------重要填写appkey that.beforeIm() //设置监听,必须先设置监听,再连接 that.nowIm() //连接融云 }, methods: { ...mapMutations({ //读取最新消息列表,并设置----------------------------重要 getAnswer:'getAnswer' }), beforeIm(){ let that = this // 连接状态监听器 RongIMClient.setConnectionStatusListener({ onChanged: function (status) { // status 标识当前连接状态 switch (status) { case RongIMLib.ConnectionStatus.CONNECTED: console.log('链接成功'); break; case RongIMLib.ConnectionStatus.CONNECTING: console.log('正在链接'); break; case RongIMLib.ConnectionStatus.DISCONNECTED: console.log('断开连接'); break; case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT: console.log('其他设备登录'); break; case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT: console.log('域名不正确'); break; case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE: console.log('网络不可用'); break; } } }); // 消息监听器 RongIMClient.setOnReceiveMessageListener({ // 接收到的消息 onReceived: function (message) { // 判断消息类型 switch(message.messageType){ case RongIMClient.MessageType.TextMessage: // message.content.content => 文字内容 //----------------------------重要-------把获取的消息存放在store中,全局公用homeIm.vue要使用 console.log('8080',message,message.content.content) that.getAnswer(message.content) break; case RongIMClient.MessageType.VoiceMessage: // message.content.content => 格式为 AMR 的音频 base64 break; case RongIMClient.MessageType.ImageMessage: // message.content.content => 图片缩略图 base64 // message.content.imageUri => 原图 URL break; case RongIMClient.MessageType.LocationMessage: // message.content.latiude => 纬度 // message.content.longitude => 经度 // message.content.content => 位置图片 base64 break; case RongIMClient.MessageType.RichContentMessage: // message.content.content => 文本消息内容 // message.content.imageUri => 图片 base64 // message.content.url => 原图 URL break; case RongIMClient.MessageType.InformationNotificationMessage: // do something break; case RongIMClient.MessageType.ContactNotificationMessage: // do something break; case RongIMClient.MessageType.ProfileNotificationMessage: // do something break; case RongIMClient.MessageType.CommandNotificationMessage: // do something break; case RongIMClient.MessageType.CommandMessage: // do something break; case RongIMClient.MessageType.UnknownMessage: // do something break; default: // do something } } }); }, nowIm(){ //自己的token------从接口获取,写到缓存 var token = JSON.parse(localStorage.getItem('userInfo')).IMUser.token//"WzrthC5f4UfuiI7dIwCQ5fwtGfqCdobpowIZkcQnj8PQOQuAJb/nIi1ayzGFwJguvbQZxbJH3x0="; RongIMClient.connect(token, { onSuccess: function(userId) { console.log('Connect successfully. ' + userId); }, onTokenIncorrect: function() { console.log('token 无效'); }, onError: function(errorCode){ var info = ''; switch (errorCode) { case RongIMLib.ErrorCode.TIMEOUT: info = '超时'; break; case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION: info = '不可接受的协议版本'; break; case RongIMLib.ConnectionState.IDENTIFIER_REJECTED: info = 'appkey不正确'; break; case RongIMLib.ConnectionState.SERVER_UNAVAILABLE: info = '服务器不可用'; break; } console.log(info); } }); } },
main.js 代码
import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import './assets/style.css' // 外部static样式 ------重要 import './assets/js/rem.js' //rem适配 ------重要 import my from './assets/js/lbc.js' //------不重要 ---自定义全局方法 import HomeNews from './components/HomeNews.vue' //自定义组件 ------重要 Vue.component('HomeNews',HomeNews) Vue.prototype.$my=my //------不重要 ---自定义全局方法 使用 this.$my.xxx Vue.config.productionTip = false new Vue({ router, store, render: h => h(App) }).$mount('#app')
store.js 全代码
import Vue from 'vue' import Vuex from 'vuex' import axios from 'axios' const API_PROXY = 'https://bird.ioliu.cn/v1/?url='; //代理 Vue.use(Vuex) export default new Vuex.Store({ state: { answer:[] }, getters: { }, mutations: { getAnswer (state, playload) {//--------------重要 let say ={ //自定义消息组件所需参数 type:1, css:'left', txt:playload.content, date:'', headImg:playload.extra } state.answer.push(say) console.log(playload) }, }, actions: { } })
homeIm.vue
//一如以往,不废话,直接代码//----------------------------------------------------重要-------------------自定义消息组件,下面会贴码确定
homeNews.vue 全代码
style.css 我自己的样式表 @charset "utf-8"; /* CSS Document 刘白超修改于2019/3/10*/ html,body{height: 100%;width: 100%;word-wrap:break-word;} *{margin: 0;padding: 0;} .tc{text-align: center} .tr{text-align: right} .tl{text-align: left} .vm{vertical-align: middle;} .vs{vertical-align: sub;} .fl{float: left;} .fr{float: right;} .fz24{font-size: .24rem;} .fz20{font-size: .2rem;} .fz18{font-size: .18rem;} .fz16{font-size: .16rem;} .fz14{font-size: .14rem;} .fz12{font-size: .12rem;} .fw{font-weight: 600;} .mr5{margin-right: .05rem} .mr10{margin-right: .10rem} .mr15{margin-right: .15rem} .mr20{margin-right: .20rem} .ml5{margin-left:.05rem;} .ml10{margin-left:.10rem;} .ml15{margin-left:.15rem;} .ml20{margin-left:.20rem;} .ml24{margin-left:.24rem;} .mt40{margin-top:.40rem;} .mt20{margin-top: .20rem;} .mt15{margin-top: .15rem;} .mt10{margin-top: .10rem;} .mt5{margin-top: .05rem;} .mb5{margin-bottom: .05rem;} .mb10{margin-bottom: .10rem;} .mb15{margin-bottom: .15rem;} .mb20{margin-bottom: .20rem;} .pt5{padding-top: .05rem;} .pt10{padding-top: .10rem;} .pt15{padding-top: .15rem;} .pt20{padding-top: .20rem;} .pt30{padding-top: .30rem;} .pb5{padding-bottom: .05rem;} .pb10{padding-bottom: .10rem;} .pb15{padding-bottom: .15rem;} .pb20{padding-bottom: .20rem;} .pl5{padding-left: .05rem;} .pl10{padding-left: .10rem;} .pl15{padding-left: .15rem;} .pl20{padding-left: .20rem;} .pl30{padding-left: .30rem;} .pr5{padding-right: .05rem;} .pr10{padding-right: .10rem;} .pr15{padding-right: .15rem;} .pr20{padding-right: .20rem;} .pr30{padding-right: .30rem;} .bgef{background: #EFEFEF;} .bgf{background: #fff;} .bgf9{background: #F99F3E} .ee {background: #eee;} .bg259{background:#259DFF !important} .colordd{color: #DD4D41} .colorf9 {color: #ff9800;} .colore5{color: #e51c23;} .colorF{color: #fff;} .color3{color: #333;} .color6{color: #666;} .color9{color: #999;} .colora1{color:#a1a1a1} .color259{color:#259DFF} .color005{color:#00559B} .colorf3{color:#F3665E} .lh24{line-height: .24rem} .lh20{line-height: .20rem;} .lh30{line-height: .30rem;} .lh40{line-height: .40rem;} .lh50{line-height: .50rem;} .lh60{line-height: .60rem;} .hide{display: none} .show{display: block} .inline{display: inline-block;} .indent2{text-indent: 2em;} .txt2{ overflow : hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } .wn{white-space:nowrap;} .flex{display: flex;} .flex1{flex:1;} .colu{flex-direction: column;} .justc{justify-content: center;} .justs{justify-content: space-between}/*两端对齐*/ .justsa{justify-content: space-around}/*分散对齐*/ .juste{justify-content: flex-end;} .alic{align-items: center} .wrap{flex-wrap:wrap} .childEnd{align-self:flex-end;} .posAbs{position: absolute;} .posRel{position: relative;} .posFix{position: fixed;} .top0{top:0;} .bottom0{bottom:0;} .left0{left:0;} .right0{right: 0;} .w100{width: 100%} .h100{height: 100%} .borBox{box-sizing: border-box;} .borderte0{border-top:1px solid #e0e0e0; } .borderbe0{border-bottom:1px solid #e0e0e0; } .borRad{border-radius:.05rem;} .over{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;} .overH{overflow: hidden} .clear{zoom:1;} .clear:after{content: "\0020";display: block;height: 0;clear: both;} .mask{width: 100%;height: 100%;background: rgba(20, 20, 20, 0.5);position: fixed;z-index: 5;top: 0;left: 0;} .cursor{cursor: pointer;} .noClick{pointer-events: none;} li{list-style:none;} a{text-decoration:none;color:#555;} a:hover{color:#555;} img{display:block;vertical-align:middle;} a img,fieldset{border:0;} i,em{font-style:normal} b,strong,th{font-weight:100;} input,textarea,select{outline:none;} textarea{resize:none;} table{border-collapse:collapse;} .btn{ width: calc(100% - .54rem); background: #259DFF; font: .2rem/.5rem ""; text-align: center; color: #fff; border-radius: 5px; margin-left: .27rem; } rem.js rem自适应单位 //例如设计稿为375,最大宽度为750,则为(375,750) !function(e,t){function n(){var n=l.getBoundingClientRect().width;t=t||540,n>t&&(n=t);var i=100*n/e;r.innerHTML="html{font-size:"+i+"px;}"}var i,d=document,o=window,l=d.documentElement,r=document.createElement("style");if(l.firstElementChild)l.firstElementChild.appendChild(r);else{var a=d.createElement("div");a.appendChild(r),d.write(a.innerHTML),a=null}n(),o.addEventListener("resize",function(){clearTimeout(i),i=setTimeout(n,300)},!1),o.addEventListener("pageshow",function(e){e.persisted&&(clearTimeout(i),i=setTimeout(n,300))},!1),"complete"===d.readyState?d.body.style.fontSize="16px":d.addEventListener("DOMContentLoaded",function(e){d.body.style.fontSize="16px"},!1)}(375,640);{{data.date}}{{data.txt}} {{data.date}}{{data.title}}{{data.txt}} {{data.date}}{{data.title}}{{data.txt}}{{data.date}}{{data.txt}}
完了,okk,文中所需icon,请自行到阿里icon下载
结尾:项目中需要配置rem。
总结
以上所述是小编给大家介绍的Vue Cli 3项目使用融云IM实现聊天功能的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!