本文共 627 字,大约阅读时间需要 2 分钟。
其实有一种方式和就是在 index.html 中引入 socket.io.js 文件
但作为单页应用 在index.html中引入东西 显然 不好 本博主 也不推荐用这种方式
安装 vue-socket.io (大神封装好的vue插件)
npm install vue-socket.io --save 注册和使用import VueSocketIO from 'vue-socket.io' Vue.use(new VueSocketIO({ debug: true, connection: 'your server url', // socket 服务器所在地址 })) 测试 页面中输出 链接成功 后表示 链接上了 socket服务器new Vue({ router, store, sockets: { // 可以用来测试 是否链接成功了 connect: function () { console.log('链接成功') }, }, render: h => h(App) }).$mount('#app') 组件中使用 监听 服务器的事件 sockets: { // 服务器事件名字 msg: function() {} // 举个例子 服务器传来 msg消息 }, // 和methods 是并列关系 methods:{} 触发事件this.$socket.emit('msg', {data}); // 第二个参数是要传递的数据
转载地址:http://wiesi.baihongyu.com/