赞
踩
2.将store挂载到vue原型
import Vue from 'vue'
import App from './App'
import uView from "uview-ui";
import store from './store'
Vue.use(uView);
Vue.prototype.$store = store
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App,
store
})
app.$mount()
3.编写store文件夹下index.js文件
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { socketTask: null, // 确保websocket是打开状态 is_open_socket: false }, getters: { }, mutations: { // 进入这个页面的时候创建websocket连接【整个页面随时使用】(客户端) connectSocketInit(state, is_open_socket) { // 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】 this.state.socketTask = uni.connectSocket({ // 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】 url: "wss://www.xxx.xxx/socket/websocket", // 你的socket地址 success(data) { console.log("websocket连接成功", data); }, }); // 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】 this.state.socketTask.onOpen((res) => { const loginObj = JSON.parse(uni.getStorageSync('loginObj'))//这里是因为我需要用到用户ID来做为参数 // console.log("WebSocket连接正常打开中...!", res); this.state.is_open_socket = is_open_socket; // 注:只有连接正常打开中 ,才能正常成功发送消息 this.state.socketTask.send({ data: JSON.stringify({ "key": "call_scrollorder_subscribe", "user_id": loginObj.id }), async success() { console.log("消息发送成功"); }, }); // 注:只有连接正常打开中 ,才能正常收到消息 this.state.socketTask.onMessage((res) => { // console.log("收到服务器内容:", JSON.parse(res.data)); const result = JSON.parse(res.data).result console.log(result) }); }) // 这里仅是事件监听【如果socket关闭了会执行】 this.state.socketTask.onClose(() => { console.log("已经被关闭了") }) }, // 关闭websocket【离开这个页面的时候执行关闭】 closeSocket(state, is_open_socket) { console.log(this.state) const _this = this this.state.socketTask.close({ success(res) { console.log("关闭成功", res) _this.state.is_open_socket = is_open_socket }, fail(err) { // console.log("关闭失败", err) } }) } }, actions: {} }) export default store
3.连接websocket
this.$store.commit('connectSocketInit',true) // 根据情况在合适的地方引入(我这里是在登录成功之后连接)
4.关闭websocket
this.$store.commit('closeSocket',false) // 退出登录时关闭websocket连接
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。