Vue integrates Tencent TIM instant messaging

Vue integrates Tencent TIM instant messaging

This article mainly introduces how to integrate Tencent TIM instant messaging with Vue, and shares it with you. The details are as follows:

Above

Preface

The project needs to have a customer service function, a user-side applet, and a customer service staff web terminal, so Tencent’s tim

Preparation

Create an application on Tencent Cloud official website and obtain the corresponding SDKAppID and corresponding key information

Installing the SDK

(1) Web project usage commands

// IM Web SDK
npm install tim-js-sdk --save
// COS SDK required to send pictures, files, and other messages
npm install cos-js-sdk-v5 --save

(2) Mini Program Project Usage Commands

// IM applet SDK
npm install tim-wx-sdk --save
// COS SDK required to send pictures, files, and other messages
npm install cos-wx-sdk-v5 --save

Introduced in main.js

import TIM from 'tim-js-sdk';
// import TIM from 'tim-wx-sdk'; // For WeChat applet environment, please uncomment this line and comment out import TIM from 'tim-js-sdk';
import COS from 'cos-js-sdk-v5';
// import COS from 'cos-wx-sdk-v5'; // For WeChat applet environment, please uncomment this line and comment out import COS from 'cos-js-sdk-v5';

// Create an SDK instance. The TIM.create() method will only return the same instance for the same SDKAppID.
  SDKAppID: 0 // When accessing, you need to replace 0 with the SDKAppID of your instant messaging application
};
let tim = TIM.create(options); // SDK instances are usually represented by tim // Set the SDK log output level. For detailed levels, see the description of the setLogLevel interface tim.setLogLevel(0); // Normal level, with a large amount of logs, recommended for access // tim.setLogLevel(1); // Release level, SDK outputs key information, recommended for production environments // Register Tencent Cloud Object Storage Service SDK (hereinafter referred to as COS SDK) as a plug-in. When the IM SDK sends messages such as files and images, it needs to use Tencent Cloud's COS service wx.$app = tim
wx.$app.registerPlugin({'cos-wx-sdk': COS})
wx.store = store
wx.TIM = TIM
 wx.dayjs = dayjs
 dayjs.locale('zh-cn')
let $bus = new Vue()
Vue.prototype.TIM = TIM
Vue.prototype.$type = TYPES
Vue.prototype.$store = store
Vue.prototype.$bus = $bus
// Listen for offline messages and notifications of session list synchronization completion tim.on(TIM.EVENT.SDK_READY, onReadyStateUpdate, this)
// Receive notification that SDK enters not ready state. SDK cannot work normally at this time tim.on(TIM.EVENT.SDK_NOT_READY, onReadyStateUpdate, this)
// Received the kickout notification tim.on(TIM.EVENT.KICKED_OUT, kickOut, this)
// Unified error handling tim.on(TIM.EVENT.ERROR, onError, this)
// Receive the pushed message, traverse event.data to get the message list data and render it to the page tim.on(TIM.EVENT.MESSAGE_RECEIVED, messageReceived, this)
// Update the conversation list tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, convListUpdate, this)
// Update the group list tim.on(TIM.EVENT.GROUP_LIST_UPDATED, groupListUpdate, this)
// Update blacklist tim.on(TIM.EVENT.BLACKLIST_UPDATED, blackListUpdate, this)
// Network status changes tim.on(TIM.EVENT.NET_STATE_CHANGE, netStateChange, this)
function onReadyStateUpdate ({ name }) {
  const isSDKReady = (name === TIM.EVENT.SDK_READY)
  if (isSDKReady) {
  //User information wx.$app.getMyProfile().then(res => {
      store.commit('updateMyInfo', res.data)
   uni.setStorageSync('name', res.data.nick);
   console.log(name,'updateMyInfo');
    })
    //Blacklist, stored in vuex wx.$app.getBlacklist().then(res => {
      store.commit('setBlacklist', res.data)
    })
  }
  store.commit('setSdkReady', isSDKReady)
}
//Kicked offline function, you need to set up re-login after being kicked offline function kickOut (event) {
  store.dispatch('resetStore')
  wx.showToast({
    title: 'You have been kicked off the line',
    icon: 'none',
    duration: 1500
  })
  setTimeout(() => {
    wx.reLaunch({
      url: '../account/login'
    })
  }, 500)
}
function onError (event) {
  // Network error, no toast pop-up && sdk not initialized, complete error if (event.data.message && event.data.code && event.data.code !== 2800 && event.data.code !== 2999) {
    store.commit('showToast', {
      title: event.data.message,
      duration: 2000
    })
  }
}
//
function checkoutNetState (state) {
  switch (state) {
    case TIM.TYPES.NET_STATE_CONNECTED:
      return { title: 'Connected to the network', duration: 2000 }
    case TIM.TYPES.NET_STATE_CONNECTING:
      return { title: 'The current network is unstable', duration: 2000 }
    case TIM.TYPES.NET_STATE_DISCONNECTED:
      return { title: 'The current network is unavailable', duration: 2000 }
    default:
      return ''
  }
}
//Network state change function function netStateChange (event) {
  console.log(event.data.state)
  store.commit('showToast', checkoutNetState(event.data.state))
}
//Message sending and receiving function messageReceived (event) {
console.log(event,'main.js');
  for (let i = 0; i < event.data.length; i++) {
    let item = event.data[i]
    if (item.type === TYPES.MSG_GRP_TIP) {
      if (item.payload.operationType) {
        $bus.$emit('groupNameUpdate', item.payload)
      }
    }
    if (item.type === TYPES.MSG_CUSTOM) {
      if (isJSON(item.payload.data)) {
        const videoCustom = JSON.parse(item.payload.data)
  console.log(item,'Homepage information')
        if (videoCustom.version === 3) {
          switch (videoCustom.action) {
            // The other party calls me case 0:
              if (!store.getters.isCalling) {
                let url = `call?args=${item.payload.data}&&from=${item.from}&&to=${item.to}&&name=`+uni.getStorageSync('name')+'&&nick='+'';
    console.log(url,'url')
                wx.navigateTo({url})
              } else {
                $bus.$emit('isCalling', item)
              }
              break
            // The other party cancels case 1:
              wx.navigateBack({
                delta: 1
              })
              break
            // The other party refuses case 2:
              $bus.$emit('onRefuse')
              break
            // The other party does not answer for 1 minute
            case 3:
              wx.navigateBack({
                delta: 1
              })
              break
            // The other party answers the call case 4:
              $bus.$emit('onCall', videoCustom)
              break
            // The other party hangs up case 5:
              $bus.$emit('onClose')
              break
            // The other party is on the phone case 6:
              $bus.$emit('onBusy')
              break
            default:
              break
          }
        }
      }
    }
  }
  store.dispatch('onMessageEvent', event)
}
function convListUpdate (event) {
  store.commit('updateAllConversation', event.data)
}

function groupListUpdate (event) {
  store.commit('updateGroupList', event.data)
}

function blackListUpdate (event) {
  store.commit('updateBlacklist', event.data)
}

This is the end of this article about Vue’s integration of Tencent TIM instant messaging. For more relevant Vue Tencent TIM instant messaging content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue custom component to realize address book function
  • Vue.js parent-child component communication development example
  • VueJs component parent-child communication method
  • Sample code for Vue2.0 component value communication
  • Collection of eight Vue component communication methods (recommended)
  • Parent-child component communication in Vue and using sync to synchronize parent-child component data

<<:  Copy fields between different tables in MySQL

>>:  Can MySQL's repeatable read level solve phantom reads?

Recommend

Batch replace part of the data of a field in Mysql (recommended)

Batch replace part of the data of a field in MYSQ...

How to implement responsive layout in vue-cli

When we are doing front-end development, we will ...

Vue close browser logout implementation example

Table of contents 1. beforeunload event 2. Unload...

Steps to deploy ingress-nginx on k8s

Table of contents Preface 1. Deployment and Confi...

Example code of javascript select all/unselect all operation in html

Copy code The code is as follows: <html> &l...

Select web page drop-down list and div layer covering problem

Questions about select elements in HTML have been...

Detailed explanation of the execution process of mysql update statement

There was an article about the execution process ...

Markup language - for

Click here to return to the 123WORDPRESS.COM HTML ...

Docker compose custom network to achieve fixed container IP address

Due to the default bridge network, the IP address...

Google Translate Tool: Quickly implement multilingual websites

Google China has released a translation tool that ...

Detailed tutorial on installing MySQL database in Linux environment

1. Install the database 1) yum -y install mysql-s...

MySQL 8.0.11 installation and configuration method graphic tutorial

The installation and configuration methods of MyS...

CentOS7 deployment Flask (Apache, mod_wsgi, Python36, venv)

1. Install Apache # yum install -y httpd httpd-de...