당신은 여기 socket.io-client
와 VueJs에 예를 들어 동적 소켓을 처리 할 수
부모 :
<MyComponent server="http://127.0.0.1:8000/"></MyComponent>
<MyComponent server="http://127.0.0.1:8000/namespaced-socket"></MyComponent>
<MyComponent :server="dynamicServer"></MyComponent>
//...
components: {
MyComponent
},
하위 구성 요소 :
import SocketIO from 'socket.io-client'
//...
export default {
name: 'MyComponent',
data() {
return {
socket: null
}
},
props: {
server: {
type: String,
required: true
}
},
methods: {
newSocket() {
let socket = SocketIO(this.$props.server, { origins: 'http://localhost:*/* http://127.0.0.1:*/*' })
this.socket = socket
this.socket.on('data', (data) => { // your server emits, ready, data, etc...
console.log('data')
// do whatever you want with `data`
})
}
},
mounted() {
this.newSocket()
}
}
부모 구성 요소 (또는 뷰)에서 템플릿에 자식 구성 요소를 동적으로 추가하는 메서드를 만들 수 있습니다 (서버가 동적으로 변경되면 자식과 같은 다른 전용 메서드를 사용하여 처리해야합니다. this.newSocket()
).
crossorigin에 문제가있을 수 있으므로 그게 내가 { origins: 'http://localhost:*/* http://127.0.0.1:*/*' }
(예 :)을 추가 한 이유입니다.
참고 :
vue-socket.io은 하나의 단일 인스턴스를 만들 수 있습니다.
잘 작동하는지 확인하고, 나는 개인적으로 그것을 일부 프로젝트에 사용합니다.
Coud 당신은 나에게 "this.socket"이 필요한만큼 설명해 주시겠습니까? –
그것은 소켓에 관한 것이 아니라 구성 요소를 통해 소켓 인스턴스를 사용하기위한 이름입니다 (다른 이름도 사용할 수 있습니다 ..) – pirs
전역 변수는 무엇입니까? 좋습니다, 감사합니다! –