1.在onload周期里进行连接
onLoad(){
//websocket连接
this.webSocketConfig()
}
methods:{
//建立socekt链接
webSocketConfig(){
this.reconnectTimer && clearTimeout(this.reconnectTimer)
this.interVal && clearInterval(this.interVal)
var that = this
var socketOpen = false;
this.socketTaskChat = uni.connectSocket({
url: this.websocketUrl + piniaData.userInfo.id,
data(){return {}},
header:{'content-type': 'application/json'},
method: 'GET',
success: res =>{
},
fail: () =>{
},
complete: () =>{
}
});
this.socketTaskChat.onError(function(res){
//连接失败,进行重连
that.handleHeart()
});
this.socketTaskChat.onClose(function(res){
});
this.socketTaskChat.onOpen(function(res){
this.reconnectTimer && clearTimeout(this.reconnectTimer)
this.interVal && clearInterval(this.interVal)
});
this.socketTaskChat.onMessage(function(res){
//接收到消息
//可以触发vuex中的网络请求,然后在需要接收消息通知的页面里使用vuex中的state数据
let data = JSON.parse(res.data)
if(data.type == 'a'){
//触发vuex中的addA方法, 修改vuex中state中的a
store.commit('addA')
}else if(data.type == 'b'){
//触发vuex中的addB方法, 修改vuex中state中的b
store.commit('addB')
}
});
},
//心跳检测
handleHeart() {
var that = this
this.interVal = setInterval(function() {
that.handleSend()
}, 5 * 1000)
},
//发送消息
handleSend() {
var that = this
var data = {
state: 1,
method: 'heartbeat'
}
this.socketTaskChat.send({
data: data,
success(res) {
clearInterval(that.interVal)
},
fail(res) {
that.reconnect()
}
});
},
// 重新连接socket
reconnect() {
var that = this
clearTimeout(this.reconnectTimer)
clearInterval(this.interVal)
this.reconnectTimer = setTimeout(() => {
that.webSocketConfig()
}, 5 * 1000)
},
}
2.为了演示,只是写一个简易版的vuex
import { createStore } from "vuex"
export default createStore(({
state: {
a: 0,
b: 0
},
mutations: {
addA(state){
state.a++
},
addB(store){
state.b++
}
}
}))
3.在页面A中监听vuex中的A, B页面中监听vuex中的B
监听到改变了,直接调接口更新页面数据