vue使用MQTT实现简单即时聊天

1,248 阅读1分钟
<!-- 我的ID是 :222 -->

<template>
	<view class="content">
		<input style="border: 1px solid #DD524D;" v-model="content" />
		<button @click="send" type="primary">发送</button>
		<view class="log">
			<view v-for="(log,index) in logs" class="" :key="index">
				{{log}}
			</view>
		</view>
	</view>
</template>

<script>
	var mqtt = require('mqtt/dist/mqtt.js')
	var client = mqtt.connect('ws://test.mosquitto.org:8080')
	export default {
		data() {
			return {
				title: '',
				logs: [],
				content:''
			}
		},
		created() {
		var self=this;
	    client.on('connect', function() {
			client.subscribe('222', function(err) {
			})
	    }).on('message', function(topic, message) {
	       self.logs.push("对方:"+message.toString())
	    })
		},
		methods: {
		send() {
		var self=this;
		client.publish('333', self.content)
		self.logs.push("我:"+self.content)
		},
		}
	}
</script>

<style>
	.content {
		text-align: center;
		height: 400upx;
		word-break: break-all;
	}
</style>