Home > Web Front-end > JS Tutorial > Detailed analysis of Vue Socket.io source code

Detailed analysis of Vue Socket.io source code

亚连
Release: 2018-06-07 11:55:14
Original
2422 people have browsed it

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;
Copy after login
import store from './yourstore'
Vue.use(VueSocketio, socketio('http://socketserver.com:1923'), store);
Copy after login

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

//
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template