vue+websocket使用总结(四)

安装sockjs-client和stompjs

npm/cnpm install sockjs-clent
npm/cnpm install stompjs

在需要使用的vue文件中引用

import SockJS from  'sockjs-client';
import  Stomp from 'stompjs';

在文件中监听websocket接口

注意:initWebsocket()方法只有在页面刷新的时候会调用,而stompClient.subscribe(’/topic/global’, function(message) {***}中的代码***在每一次接收到数据时都会触发。

	initWebsocket() {
				var monster = null;
				var steps = [];
				var stepSort = [];
				var id = '';
				var firstId = '';
				var imgSrc = '';
				var subTitle = '';

				var socket = new SockJS(this.httpUrl + "/ws");
				var stompClient = Stomp.over(socket);
				this.$nextTick(() => {
					stompClient.connect({}, function(frame) {
						stompClient.subscribe('/topic/global', function(message) {
							var url = '';
							this.imgs = [];
							this.contentSrc = '';
							this.isUrl = true;

							//						this.listData = JSON.parse(message.body);
							//						console.log('date', this.getCurrentDate(2));
							//message为一个数组,传递流程各环节的名称
							//						console.log('message1', message);
							//						console.log('message', message.body);
							this.ifShow = false;
							monster = JSON.parse(message.body);
							//						console.log('steps', monster.stepIds);
							steps = monster.stepIds;
							stepSort = monster.stepSort.split(",");
							//						this.title = monster.name;
							this.title = monster.name + "自动化扩充流程";
							//							this.imgs = [];
							//渲染整体流程
							stepSort.forEach(stepIndex => {
								steps.forEach(step => {
									//此处不判断showType了
									//							if(step.showType == 0) {
									if(stepIndex == step.id) {
										id = step.id;
										imgSrc = (step.icon == null) ? this.items.imgSrc : step.icon;
										subTitle = (step.name == null) ? this.items.subTitle : step.name;
										this.imgs.push({
											'id': id,
											'imgSrc': imgSrc,
											'subTitle': subTitle
										});

										//取得第一个需要展示的url展示在页面下方

										if(url == '') {
											firstId = step.id;
											url = (step.url == null) ? this.url : step.url;
											console.log("url-" + url);
											this.contentSrc = url;
										}
									}
								});
							});

						}.bind(this));
					}.bind(this));
				});

			},
			mounted() {
			this.initWebsocket();
			//			this.test();
			this.flowWebsocket();
		}

你可能感兴趣的:(vue学习笔记)