0
我是Vue.js的新手,想知道如何在Vue中完成這項工作,而不是jQuery?Vue.js + Socket.io - 在實時應用中添加元素?
的socket.io和jQuery將append
瀏覽器上的<li>
每次當有人輸入一些東西。
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
</head>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function() {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
這是如何在Vue中完成的?
我想:
$(function() {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
var app = new Vue({
el: '#app',
data: {
message: "Hello World"
},
created: function() {
socket.on('chat message', function(data) {
this.message = data.message;
}.bind(this));
}
});
});
在我的新HTML:
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
<span id="app">{{ message }}</span>
</form>
它沒有明顯的工作。
任何想法?
什麼是',zthis'? – laukok
@ teelou這是一個錯字 –
也,你有兩個id =「應用程序」在HTML中。 – laukok