This article mainly introduces the interpretation of the Vue Socket.io source code. Now I share it with you and give you a reference.
Background
There is a project that started to be reconstructed in December this year, and the project involves sockets. But the socket uses a package packaged by a previous developer (this has been complained by current members about why they don’t use the wheel that has been tempered for thousands of times). Therefore, taking advantage of this refactoring opportunity, vue-socket.io is introduced, and socket.io is used as the backend. I was also curious and took a look at the source code of vue-socket.io (I won’t say it’s because the documentation of this library is too brief. I just looked at the source code to understand how to use it for stability)
Start
File structure
We mainly look at the three files under src. We can see that the library is used Observer pattern
Main.js
// 这里创建一个observe对象,具体做了什么可以看Observer.js文件 let observer = new Observer(connection, store) // 将socket挂载到了vue的原型上,然后就可以 // 在vue实例中就可以this.$socket.emit('xxx', {}) Vue.prototype.$socket = observer.Socket;
import store from './yourstore' Vue.use(VueSocketio, socketio('http://socketserver.com:1923'), store);
If we want to use this library, we usually write the code like this (Figure 2 above). The connection and store in Figure 1 above are the last two parameters of Figure 2 respectively. They mean the URL of the socket connection and the store of vuex respectively. Figure 1 is to pass these two parameters into the Observer, create a new observer object, and then mount the socket property of the observer object on the Vue prototype. Then we can directly this.$sockets.emit('xxx', {}) in the Vue instance
//
The above is the detailed content of Detailed analysis of Vue Socket.io source code. For more information, please follow other related articles on the PHP Chinese website!