Dea*_*ato 2 javascript websocket vue.js nuxt.js
所以我想使用 NuxtJs 框架使用 VueJs 制作一个 Web 套接字客户端,这是我的组件
export default {
data() {
return {
connection: null,
}
},
created() {
console.log("Starting connection to WebSocket Server")
this.connection = new WebSocket("wss://echo.websocket.org")
this.connection.onmessage = function(event) {
console.log(event);
}
this.connection.onopen = function(event) {
console.log(event)
console.log("Successfully connected to the echo websocket server...")
}
},
head() {
return {
title: 'Web Socket',
meta: [
{
hid: 'description',
name: 'description',
content: 'Web socket'
}
]
}
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用 Ms Edge 作为浏览器,我尝试使用 vue-native-socket 和其他套接字包,但仍然收到相同的错误“Websocket 未定义”
我不是 Websocket 专家,但据我所知,这只能在客户端使用。
您可以尝试跟进这个答案:/sf/answers/4742608531/
created() {
if (process.client) {
// the code in this block will only run on client side
console.log("Starting connection to WebSocket Server")
this.connection = new WebSocket("wss://echo.websocket.org")
this.connection.onmessage = function(event) {
console.log(event);
}
this.connection.onopen = function(event) {
console.log(event)
console.log("Successfully connected to the echo websocket server...")
}
}
}
Run Code Online (Sandbox Code Playgroud)
这将防止编写在钩子内部的代码created()在服务器端和客户端上被触发(因此在服务器上出现错误)。因为created()在服务器端和客户端都可用,如下所述: https: //nuxtjs.org/docs/2.x/concepts/nuxt-lifecycle/
| 归档时间: |
|
| 查看次数: |
1852 次 |
| 最近记录: |