web vue+IM即时通讯

1.web即时通讯

https://cloud.tencent.com/document/product/269/75319(文档)

https://web.sdk.qcloud.com/im/doc/zh-cn/TIM.html(API)

2.main中引入

// 从v2.11.2起,SDK 支持了 WebSocket,推荐接入;v2.10.2及以下版本,使用 HTTP
// v2.24.0起,SDK 支持使用本地审核插件
import TIM from 'tim-js-sdk';
import TIMUploadPlugin from 'tim-upload-plugin';
import TIMProfanityFilterPlugin from 'tim-profanity-filter-plugin';let options = {SDKAppID: 1400793822 // 接入时需要将0替换为您的即时通信 IM 应用的 SDKAppID
};
// 创建 SDK 实例,`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
let tim = TIM.create(options); // SDK 实例通常用 tim 表示// 设置 SDK 日志输出级别,详细分级请参见 setLogLevel https://web.sdk.qcloud.com/im/doc/zh-cn/SDK.html#setLogLevel 接口的说明
tim.setLogLevel(0); // 普通级别,日志量较多,接入时建议使用
// tim.setLogLevel(1); // release 级别,SDK 输出关键信息,生产环境时建议使用// 注册腾讯云即时通信 IM 上传插件
tim.registerPlugin({'tim-upload-plugin': TIMUploadPlugin});// 注册腾讯云即时通信 IM 本地审核插件
tim.registerPlugin({'tim-profanity-filter-plugin': TIMProfanityFilterPlugin});Vue.prototype.TIM = TIM
Vue.prototype.tim = tim

3.引入下载好debug

4.在需要的页面

import { genTestUserSig } from '@/debug/GenerateTestUserSig'首先要登录  
login(){
    let userSig=genTestUserSig(this.userName).userSig
    let promise = this.tim.login({userID: this.userName, userSig: userSig});
    promise.then(function(imResponse) {
    console.log(imResponse.data); // 登录成功
    if (imResponse.data.repeatLogin === true) {
        // 标识帐号已登录,本次登录操作为重复登录。v2.5.1 起支持
        console.log(imResponse.data.errorInfo);
        
    }
    }).catch(function(imError) {
    console.warn('login error:', imError);
    });
},登录成功后需要加入群组joinGrop(){let promise = this.tim.joinGroup({ groupID: '10012345' });promise.then(function(imResponse) {console.log(imResponse.data.status) switch (imResponse.data.status) {case this.TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL: // 等待管理员同意break;case this.TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功console.log(imResponse.data.group); // 加入的群组资料break;case this.TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中break;default:break;}}).catch(function(imError){console.warn('joinGroup error:', imError); // 申请加群失败的相关信息});
},发送文字sendMessage(){let message = this.tim.createTextMessage({to: '10012345',conversationType: this.TIM.TYPES.CONV_GROUP,payload: {text: this.message},needReadReceipt: true});let promise = this.tim.sendMessage(message);let _this=thispromise.then(function(imResponse) {_this.message=''_this.msglist=[..._this.msglist,...[imResponse.data.message]]}).catch(function(imError) {});
},然后就是监听mounted() {let onMessageReceived = function(event) {this.msglist=[...this.msglist,...event.data]};this.tim.on(this.TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived,this);
},