VUE.js实现 angular.js /goodhelper(这个人博客很厉害,可以关注)<!DOCTYPE html><html><head><meta charset="UTF-8"/><title>My WebSocket</title><script src="/vue/2.5.10/vue.js"></script></head><body>Welcome To My WebSocket.<br/><br/><div id="ws"><input id="text" type="text"/><button οnclick="sendMsg()">Send</button><button οnclick="closeWS()" :disabled="!opened">Close</button><button οnclick="openWS()" :disabled="opened">Open</button><div v-html="msg"></div></div></body><script type="text/javascript">var websocket = null;var wsVue = new Vue({el: '#ws',data: {msg: "welcome to my websocket...<br/>",opened: false},mounted: function () {initWs();}});function initWs() {//check if your browser supports WebSocketif ('WebSocket' in window) {websocket = new WebSocket("ws://(服务端的地址,且支持跨域,不需要添加http://,只需要:端口:例如:192.168.1.73:10101)/my-websocket");}else {alert('Sorry, websocket not supported by your browser.')}//Error callbackwebsocket.onerror = function () {setMessageContent("error!");wsVue.opened = false;};//socket opened callbackwebsocket.onopen = function (event) {setMessageContent("websocket opened");wsVue.opened = true;}//message received callbackwebsocket.onmessage = function (event) {setMessageContent(event.data);}//socket closed callbackwebsocket.onclose = function () {setMessageContent("websocket closed");wsVue.opened = false;}//when browser window closed, close the socket, to prevent server exceptionwindow.onbeforeunload = function () {websocket.close();}}//update message to vue and then in divfunction setMessageContent(content) {wsVue.msg += content + '<br/>';}//click to close the websocketfunction closeWS() {websocket.close();wsVue.opened = false;}//click to open the websocketfunction openWS() {initWs();}//click to send messagefunction sendMsg() {var message = document.getElementById('text').value;websocket.send(message);}</script></html>
1200字范文,内容丰富有趣,写作的好帮手!