uni-app全局使⽤websocket收发数据
在上⼀篇《uniapp全局使⽤websocket》中有⼈提出没有写websocket接收数据,现在继续完善优化⼀下我们store⽂件夹底下的index.js⽂件,代码如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
socketTask: null,
websocketData: {}, // 存放从后端接收到的websocket数据
},
mutations: {
setWebsocketData (state, data) {
state.websocketData = data
}
},
actions: {
websocketInit ({ state, dispatch }, url) {
state.socketTast = tSocket({
url, // url是websocket连接ip
success: () => {
console.log('websocket连接成功!')
},
fail: e => {
console.log('连接失败' + e)
}
})
Open(() => dispatch('websocketOnOpen'))
Message(res => dispatch('websocketOnMessage', res))
Close(e => dispatch('websocketOnClose'))
Error(e => dispatch('websocketOnError'))
},
websocketOnOpen ({ commit }) {
console.log('WebSocket连接正常打开中...!')
},
// 收到数据
websocketOnMessage ({ commit }, res) {
console.log('收到服务器内容:' + res.data)
if (res.data !== '连接成功') {
commit('setWebsocketData', (res && JSON.parse(res.data) || null))
}
},
websocketOnClose ({ commit, dispatch }) {
console.log('WebSocket连接关闭')
},
websocketOnError ({ commit, dispatch }) {
console.log('WebSocket连接错误')
},
websocketClose ({ state }) {
websocket和socketif (!state.socketTast) return
state.socketTast.close({
success (res) {
console.log('关闭成功', res)
},
fail (err) {
console.log('关闭失败', err)
}
})
},
// 发送数据
websocketSend ({ state }, data) {
uni.sendSocketMessage({
data,
success: res => {
console.log('发送成功', res)
},
fail: e => {
console.log('发送失败', e)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论