通过node index.js启动
index.js
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const path = require('path')
app.use(bodyParser.json())//设置json解析
const list = ['11','22'] //定义全局的消息列表
app.get('/',(req,res) => {
res.sendFile(path.resolve('./index.html'))
})
app.get('/list', (req,res)=> {
res.end(JSON.stringify(list))
})
app.post('/send', (req,res)=> {
let info = req.body.message;
list.push(info)
res.end(JSON.stringify(list));
})
app.post('/clear', (req,res)=> {
list.length = 0
res.end(JSON.stringify(list))
})
app.listen(3000,()=>{
console.log("服务器启动~~3000")
})
对应的index.html
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<input v-model="message">
<button v-on:click="send">发送</button>
<button v-on:click="clear">清空</button>
<div v-for="item in list">{{item}}</div>
</div>
<script>
const host = 'http://localhost:3000'
var app = new Vue({
el: '#app',
data: {
list: [],
message: 'Hello Vue!'
},
methods: {
send: async function () {
let res = await axios.post(host + '/send', {
message: this.message
})
this.list = res.data
},
clear: async function () {
let res = await axios.post(host + '/clear')
this.list = res.data
}
},
mounted: function () {
setInterval(async () => {
const res = await axios.get(host + '/list')
this.list = res.data
}, 1000);
}
});
</script>
</body>
</html>