vue3.2最新語法使用socket.io實(shí)現(xiàn)即時(shí)通訊詳解
socket.io
socket.io是即時(shí)通訊必需的插件,要和后端配合使用socket.io才可以,前端使用【socket.io-client】,旨在讓你少走彎路~
先安裝【socket.io-client】
yarn add socket.io-client -S
安裝后再新建ts,以插件形式引入
在utils文件夾下新建socket.ts
代碼如下
// 新建ts 以插件形式引入
import io from 'socket.io-client';
export default {
install: (app: any, { connection, options }) => {
const socket = io(connection, options);
app.config.globalProperties.$socket = socket;
app.provide('socket', socket);
},
};在main.ts引入socket.ts
import SocketIO from '/@/utils/socket';
// socket
// 配置
const socketOptions = {
autoConnect: true, // 自動(dòng)連接
transports: ['websocket'], // 指定為websocket連接
reconnect: true,
reconnectionAttempts: 5, // 重連次數(shù)
};
app.use(SocketIO, {
connection: 'wss://yyds.it98k.cn',
options: socketOptions,
});
鏈接上socket 執(zhí)行登錄方法
一般鏈接上socket要執(zhí)行一個(gè)登錄方法,這個(gè)方法一般就調(diào)用一次,所以要選擇在合適的位置,也就是在剛登陸后立馬就要調(diào)用,vue2的時(shí)候在vuex里getInfo接口里執(zhí)行登錄操作,但是在vue3中this指向比較難搞,又是使用的pinia,就不太好弄了,故我們選擇在App.vue里執(zhí)行登錄方法
App.vue代碼如下
項(xiàng)目使用的【pinia】
<script setup lang="ts">
/** 執(zhí)行socketio登錄 看不懂的加我v 1115009958 交流*/
import { computed } from 'vue';
import { useUserStore } from '/@/store/modules/user';
const socket: any = inject('socket');
const userStore = useUserStore();
const getUserInfo = computed(() => {
const { info } = userStore.$state;
return info;
});
watch(getUserInfo, (newVal) => {
socket.emit('login', {
nickname: newVal.nickname,
_id: newVal._id,
});
});
</script>- ps:watch監(jiān)聽是
確保getUserInfo能讀取到$state中的數(shù)據(jù),再調(diào)用socket.emit('login')方法
觸發(fā)emit、on方法
如果要觸發(fā)emit、on方法,在頁面中這樣做
<script setup lang="ts">
/** 使用inject通信方法接收socket實(shí)例*/
const socket: any = inject('socket');
// 使用on監(jiān)聽事件
socket.on('message', (res: any) => {
console.log('接收到的數(shù)據(jù) ', res);
});
// 使用emit發(fā)送事件
socket.emit('sayTo',{ message:"test" });
</script>以上就是vue3.2最新語法使用socket.io實(shí)現(xiàn)即時(shí)通訊詳解的詳細(xì)內(nèi)容,更多關(guān)于vue3.2 socket.io即時(shí)通訊的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解vuex持久化插件解決瀏覽器刷新數(shù)據(jù)消失問題
這篇文章主要介紹了詳解vuex持久化插件解決瀏覽器刷新數(shù)據(jù)消失問題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-04-04
vue實(shí)現(xiàn)循環(huán)滾動(dòng)列表
這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)循環(huán)滾動(dòng)列表,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-06-06
vue結(jié)合leaflet實(shí)現(xiàn)鷹眼圖
本文主要介紹了vue結(jié)合leaflet實(shí)現(xiàn)鷹眼圖,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
vue引入微信sdk 實(shí)現(xiàn)分享朋友圈獲取地理位置功能
這篇文章主要介紹了h5 vue引入微信sdk 實(shí)現(xiàn)分享朋友圈,分享給朋友,獲取地理位置功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-07-07
Ant Design Vue pro 動(dòng)態(tài)路由的實(shí)現(xiàn)和打包方式
這篇文章主要介紹了Ant Design Vue pro 動(dòng)態(tài)路由的實(shí)現(xiàn)和打包方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06

