简体   繁体   中英

How to bind server side data to some html element using vue.js

I have a server-side node app and I would like to add some basic web interface for the app. I'm following introductory vue.js tutorials , but don't see anything related to what I'm trying to do.

Imagine, that I have this server-side node app:

var state = { message: 'hello world', count: 0 };
function work() {
    state.message = 'hello world ' + (state.count++);
}
setInterval(work, 1000);

Now, to add the web interface for the app I added some basic http server code:

var state = { message: 'hello world', count: 0 };
function work() {
    state.message = 'hello world ' + (state.count++);
}
setInterval(work, 1000);

var http = require('http');
var port = process.env.PORT || 1337;

http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('message: ' + state.message+'\n');
}).listen(port);

It "works": if I refresh page I'll see value of my state of the app. Now I want to update this simple app to automatically update view on client side to reflect any changes to the state that were done on server side. I could change that web page to automatically refresh every second or something like that to reflect any server changes, but I'm looking for something that was designed to do exactly that. Eventually I'll need to make that web interface to be able to change some of that server state (to change state.count for example). How can this be done with vue.js , or I should use something else for that or should I simply code all that logic to pass updated state.count using http POST/GET to my web interface?

What you are describing is websockets. With your current code, you are creating a connection, and then closing the connection when you call res.end .

You want something that allows an open connection between server and front-end without needing a constant request. Take a look at https://socket.io/ and specific Vue implementation:

https://medium.com/@michaelmangial1/getting-started-with-vue-js-socket-io-8d385ffb9782

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM