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

How to use MySQL 5.7 temporary tablespace to avoid pitfalls

Introduction MySQL 5.7 aims to be the most secure...

Detailed explanation of basic data types in mysql8.0.19

mysql basic data types Overview of common MySQL d...

Implementing circular scrolling list function based on Vue

Note: You need to give the parent container a hei...

Detailed explanation of the steps of using ElementUI in actual projects

Table of contents 1. Table self-sorting 2. Paging...

jQuery implements all selection and reverse selection operation case

This article shares the specific code of jQuery t...

Tutorial on installing Tomcat server under Windows

1 Download and prepare First, we need to download...

VSCode+CMake+Clang+GCC environment construction tutorial under win10

I plan to use C/C++ to implement basic data struc...

Detailed explanation of DIV+CSS naming rules can help achieve SEO optimization

1. CSS file naming conventions Suggestion: Use le...

Why can't my tomcat start?

Table of contents Phenomenon: Port usage: Spellin...

How to package the uniapp project as a desktop application

Installing Electron cnpm install electron -g Inst...

Docker installs ClickHouse and initializes data testing

Clickhouse Introduction ClickHouse is a column-or...

Essential bonus items for optimizing and packaging the front end of Vue projects

Table of contents Preface 1. Routing lazy loading...