Home  >  Article  >  Web Front-end  >  How to use websocket in vue project (steps)

How to use websocket in vue project (steps)

PHPz
PHPzOriginal
2023-04-13 13:37:425266browse

WebSocket is a protocol for full-duplex communication over a single TCP connection. Vue is a popular JavaScript framework for building user interfaces. Combining WebSocket and Vue can achieve the effects of real-time data communication and dynamically updating UI.

In this tutorial, we will learn how to use WebSocket in a Vue application.

Step 1: Install the WebSocket library

Use npm or yarn to install the WebSocket library. Enter the following command in the terminal:

npm install vue-websocket

or

yarn add vue-websocket

Vue-Websocket is a lightweight WebSocket client for Vue.js that allows you to easily establish WebSocket connections, transfer events Stored in the Vue component and automatically cleared when the component is mounted.

Step 2: Create a WebSocket instance

In the Vue component, use VueWS to create a WebSocket instance. When the component is created, use the created or mounted hook to instantiate WebSocket and connect to the server:

import VueWS from "vue-websocket";

export default{
    name: "WebSocketDemo",
    mixins: [VueWS],
    created() {
        this.connect();
    },
    methods: {
        handleData(data) {
            console.log(data);
        }
    }
}

We mixed VueWS into the Vue component, which provides There are connect() and send() methods, as well as an onmessage() callback.

In this example, we use the connect() method to connect to the WebSocket server and pass two parameters, one is the connection address, and the other is the options object, which can be used to configure the WebSocket connection. In addition, we declared the handleData() method in the Vue component and printed the data for later processing.

Step 3: Send a message

You can use the send() method to send a message. Call the send() method in the method of the Vue component, passing the data to be sent as a parameter:

this.send("Hello, world!");

Step 4: Close the connection

Use the close() method to close the WebSocket connection:

this.close();

Step 5: Process the received message

Call onmessage(callback) to register a listener, which will be called when WebSocket receives a message:

this.onmessage = function (event) {
    console.log(event.data);
};

Or, use handleData( ) method processes the received data, as shown in the sample code.

Step 6: Complete Example

Here is a complete Vue component example, which includes connecting to the WebSocket server, sending and receiving messages, and closing the WebSocket connection after creating the component:



<script>
import VueWS from "vue-websocket";

export default {
    name: "WebSocketDemo",
    mixins: [VueWS],
    created() {
        this.connect("ws://localhost:8080");
    },
    data() {
        return {
            message: ""
        };
    },
    methods: {
        handleData(data) {
            this.message = data;
        },
        sendMessage() {
            this.send(&quot;Hello, world!&quot;);
        },
        closeConnection() {
            this.close();
        }
    }
};
</script>

In this example, we use the VueWS plug-in to create a WebSocket instance, and use the connect() method to connect to the WebSocket server after the component is created. We have defined some methods in the Vue component, such as handleData(), which has a data parameter for processing the received data.

The sendMessage() method is used to send messages, and the closeConnection() method is used to close the WebSocket connection. We also define a message variable to display the received message on the Vue component.

In the Vue template, we use the {{message}} directive to display the received message.

Summary

Using Vue-Websocket, the Vue application can communicate with the server in real time through the WebSocket protocol. This is a very effective way to implement two-way data flow and update the UI in real time. . Using Vue-Websocket to build Vue applications will make business processing more efficient.

The above is the detailed content of How to use websocket in vue project (steps). For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:html5 html differenceNext article:html5 html difference