2017-11-22 10 views
0

다른 URL/네임 스페이스로 어떻게 동적 소켓을 사용할 수 있습니까?구성 요소에서 동적 소켓 URL을 사용하는 방법?

나는 먼저 vue-socket.io으로 시도했습니다.

main.js

import VueSocketio from 'vue-socket.io'; 
Vue.use(VueSocketio, 'http://localhost:8091/notification'); 

내가이 동적으로 변경할 것입니다하지만 난 그것을 할 수있는 방법을 찾아야하지 않았다 URL.


는 또한 구성 요소에 socket.io 클라이언트로했습니다.

구성 요소 :

import io from 'socket.io-client'; 
const adminSocket = io('http://localhost:8091/notification'); 

하지만 그냥 모든 시간을 pendidng.

답변

1

당신은 여기 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은 하나의 단일 인스턴스를 만들 수 있습니다.

잘 작동하는지 확인하고, 나는 개인적으로 그것을 일부 프로젝트에 사용합니다.

+0

Coud 당신은 나에게 "this.socket"이 필요한만큼 설명해 주시겠습니까? –

+0

그것은 소켓에 관한 것이 아니라 구성 요소를 통해 소켓 인스턴스를 사용하기위한 이름입니다 (다른 이름도 사용할 수 있습니다 ..) – pirs

+1

전역 변수는 무엇입니까? 좋습니다, 감사합니다! –