vue tab数据是查询接口 + websocket 里面的 (socket数据是实时更新)---更新2个bug

react和vue的比较

相同
1)vitual dom
2)组件化
3)props,单一数据流

不同点
1)react是jsx和模板;(jsx可以进行更多的js逻辑和操作)
2)状态管理(react)
3)对象属性(vue)
4)vue:view——medol之间双向绑定
5)vue:组件之间的通信(props,callback,emit)

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

import Cookies from ‘js-cookie’;
export default {
data () {
return {
webstock:null,
// 列表全部数据 Alldata = 之前接口的 historyData + websocket的数组 list_arry
Alldata:[],
// list_arry:[],
// list_arry:[{deviceid:“00000”,ip:“192.168.0”,type:“未开启”,time:“2019-04-16 00:00:00”}],
// 定义全局变量
send_variable:‘’,
station_Id:‘’,

            data1: [
                {
                    title: '1号线',
                    expand: true,
                    children: [
                        {
                            title: '预留01站'
                        },
                        {
                            title: '预留02站'
                        },
                        {
                            title: '预留03站'
                        },
                        {
                            title: '预留04站'
                        },
                        {
                            title: '预留05站'
                        }
                    ]
                },
                {
                    title: '2号线',
                    expand: true,
                    children: [
                        {
                            title: '西直门站'
                        },
                        {
                            title: '车公庄站'
                        },
                        {
                            title: '阜成门站'
                        },
                        {
                            title: '复兴门站'
                        }
                    ]
                },
            ],
            ajaxHistoryData:[],
            dataCount:1,// 初始化信息总条数
            currentPage:1, //当前页
            pageSize:10,// 每页显示多少条
            below: 0, //下一页或者上一页的第一项索引值 
            historyColumns: [   
                {title: '设备名称',key: 'deviceName',width: 150,align: 'center'},
                {title: '设备IP',key: 'ip',width: 150,align: 'center'},
                // {title: '设备id',key: 'deviceId',width: 150,align: 'center'},
                {title: '设备状态',key: 'type',width: 120,align: 'center'},
                {title: '时间',key: 'time',align: 'center'},
            ],
            historyData:[],
            testData:[{ "deviceId":"00000","ip":"192.168.001","type":"未开启","time":"2019-04-11 00:00:00"}],
        }
    },
    methods: {
        // 拿服务节点去调接口
        get_serverNodeId(){
            this.$axios({
                method: 'get',
                url: this.baseURL + '/device/DeviceInfo/get_LineAndStation',
                params: {
                    // 0101ZZ00100000001    tcc  既有线路又有车站    
                    // 01010100100000001    occ  只有车站   
                    // 01010103100000000    sc    空
                    manageNodeid: this.$store.state.user.serverNodeId,
                }
            }).then(res => {
                console.log("服务调接口:", res.data)
                this.data1 = [];
                if (!res.data) return false; 

                let tree = [];
                res.data.map(v=>{
                    // console.log("vvvvvvv", v.stationInfo);
                    let _tempTree = {};
                    _tempTree.title = v.line.lineName;
                    // _tempTree.expand = true; // 线路里面的车站会展开
                    _tempTree.children = [];
                    //  console.log("vvvvvvv111111111111", v.stationInfo);
                    if (!v.stationInfo) return false; //如果v.stationInfo为 null 直接return
                    v.stationInfo.map(station=>{
                        let _tempStation = {'title':station.stationSname,'tccStationId':station.tccStationId,'linId':v.line.lineId};
                        // let _tempStation = {'title':station.stationSname, 'linId':v.line.lineName};
                        _tempTree.children.push(_tempStation)
                    })
                    tree.push(_tempTree)
                })
                this.data1 = tree;
            }).catch();
        },
        // 获取历史记录信息
        handleListApproveHistory(){
            // 保存取到的所有数据
            this.ajaxHistoryData = this.testData;
            this.dataCount = this.testData.length;
            // 初始化显示,小于每页显示条数,全显,大于每页显示条数,取前每页条数显示
            if(this.testData.length < this.pageSize){
                this.historyData = this.ajaxHistoryData;
            }else{
                this.historyData = this.ajaxHistoryData.slice(0,this.pageSize);
            }                    
        },
        //index当前页码
        changepage(index){
            this.currentPage = index;
            let sessionId = Cookies.get('status');
        },
        select_change(data) {
            console.log("radio单选:",data);
            // console.log("radio单选:",data[0].tccStationId);
            // console.log("radio单选:",data[0].linId);
            let _lineId = data[0].linId;
            var station_Id = data[0].tccStationId;
             this.station_Id = data[0].tccStationId.substring(2,4) // 截掉前2位,保留后2位
            //  console.log("打印station_Id:",this.station_Id);
            this.$axios({
                method: 'post', 
                data: this.$qs.stringify({
                    manageNodeid:'01010100100000001',
                    lineId: _lineId,
                    stationId: this.station_Id,
                }),
                headers: { 'Content-Type': 'application/x-www-form-urlencoded'},                
                url: this.baseURL + '/device/DeviceInfo/list_Records', 
            })
            .then((res)=> {
                if(res.status == "200"){
                    console.log("列表数据",res.data.list)
                    this.historyData = res.data.list;  //把结果拿到的数据赋给table
                    this.dataCount = res.data.total; //所有的条数 

                    this.initWebSocket(); // 开启WebSocket长连接

                }
            })
            .catch((error) =>{})  


        },
        /**
         * webstocket 开启长连接
         */
        initWebSocket() {
            var this1 = this;
            //页面刚进入时开启长连接
            const webstock = new WebSocket("ws://192.168.25.51:9999");
            /**
             * webstock连接成功
             */
            var this2 = this;
            webstock.onopen = function (onopen) {
                console.log("websocket open 连接成功", onopen);

                // setInterval(function(){
                    // 定义全局变量
                    this2.send_variable = '0x01000101' + "/" + this2.station_Id,
                    console.log("请求车站id:", this2.station_Id);
                    console.log("请求id:",  this2.send_variable);
                    webstock.send(JSON.stringify(this2.send_variable));
                // },1000)
            }
            /**
             * webstock出错
             */
            webstock.onerror = function (event) {
                webstock.close(event);
                console.log("websocket error");
            }
            /**
             * webstock接收消息
             */
            webstock.onmessage = function (message) {
                
                console.log( '返回的message', message);
            
                // console.log( '返回2', message.data);
                let one; // 第一个 ","后内容
                let two; // 第二个 ","后内容
                let first =  message.data.indexOf(",") + 1; // 从第一个 "," 算起( +1表示不包括该 ",")
                let knew_list =  message.data.indexOf(" ", first); // 第一个 "," 后的第一个空格
                let _comma =  message.data.indexOf(",", first); // 第一个","后的第一个","(即第二个 ",")
                if (_comma == -1) {
                    one =  message.data.substring(0, knew_list);
                    two =  message.data.substring(knew_list).substring(1,  message.data.length);
                } else {
                    one =  message.data.substring(0, _comma);
                    two =  message.data.substring(_comma).substring(1,  message.data.length);
                }
                    // console.log("one:",one);
                    // console.log("two",two);
                     let list_arry = JSON.parse(two);
                    // console.log( 'list_arry', JSON.parse(two));
                    console.log( 'list_arry', list_arry);
                    let arr = list_arry;
                    console.log("arr",arr);
                    // 如果之间拿查询列表里面的id 和 socke里面的 id进行判断是否相等,那么tab数据只有 查询的数据,打印的时候也有 time 和type就是不显示在tab上,原因是因为,socket里面的数据你塞给 tab的。
                    //所以需要 定义一个 变量数组  匹配前先清空一下数组。 在 再查询的数组里面 定义一个变量对象   把tab需要的值用新的变量 赋值拿过来 ,再进行匹配,在赋值。
                    //然后在 push  
                    // 在把tab的数组 赋给新定义的数组


                    //  tab 数组的值 是 2个地方拿来的  需要拼接在一起
                    // 定义一个新的数组去接收
                    // 循环套循环 - 定义新的对象存需要的值,- 在匹配id   相等了 就赋值  
                    // 把赋值放进数组里面
                    // 把tab 数组 赋给定义的新数组
                let new_arr = [];

                this2.historyData.map(v=>{
                    console.log("vvvvv",v);

                    let new_list = {}

                    new_list.deviceId = v.deviceId;
                    new_list.ip = v.ip;
                    new_list.deviceName = v.deviceName;
                    arr.map(item=>{
                        let new_time = item.time;
                        new_time = item.time.slice(0, 4) + "-" + item.time.slice(4, 6) + "-" + item.time.slice(6, 8)  + " " + item.time.slice(8, 10) + ":" + item.time.slice(10, 12) + ":" + item.time.slice(12, 14);
                        console.log("item", item);
                        console.log( '时间格式', new_time);
                        if(v.deviceId === item.deviceid){
                            new_list.type = item.type;
                            new_list.time = new_time;
                        }
                      
                    })
                   new_arr.push(new_list)
                })
                this2.historyData = new_arr
            }
        },
        /**
         * webstock关闭
         */
        websocketclose(e) {
            console.log("WebSocket连接关闭");
            setTimeout(() => {
                this.initWebSocket();
                console.log("socket正在重连...");
            }, 5000);
        },

    },
    created(){
        // console.log("线路和车站:",this.$store.state.parameter.lineStation);
        this.handleListApproveHistory();
        console.log("服务节点", this.$store.state.user.serverNodeId);
        this.get_serverNodeId(); //拿服务节点去调接口
    },
    mounted(){
    //    this.initWebSocket(); // 开启WebSocket长连接 
    },
    destroyed() {

//页面销毁时关闭长连接
this.websocketclose();
},
}



**二:新需求**


**要求初始化进来页面时, 树的 第一个节点 展开, 第一个节点下的第一个 值默认选中, 并且会去请求后台,加载右边的列表数据。**


**先上效果图:**


![](https://img-blog.csdnimg.cn/20190418152048735.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxNjQ2MjQ5,size_16,color_FFFFFF,t_70)


**在树循环 后 操作如下:**


**默认的操作:**



                    //默认展开第一个节点,默认选中第一个节点下的第一个值
                    if(tree.length>0){
                       tree[0].expand = true; 
                       if(tree[0].children.length>0){
                           tree[0].children[0].selected = true;
                           console.log("tree[0].children[0]",tree[0].children[0]);
                        }
                    }

用默认去加载列表:



//默认展开第一个节点,默认选中第一个节点下的第一个值
if(tree.length>0){
tree[0].expand = true;
if(tree[0].children.length>0){
tree[0].children[0].selected = true;
console.log(“tree[0].children[0]”,tree[0].children[0]);

总结

前端资料汇总

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

  • 框架原理真的深入某一部分具体的代码和实现方式时,要多注意到细节,不要只能写出一个框架。

  • 算法方面很薄弱的,最好多刷一刷,不然影响你的工资和成功率😯

  • 在投递简历之前,最好通过各种渠道找到公司内部的人,先提前了解业务,也可以帮助后期优秀 offer 的决策。

  • 要勇于说不,对于某些 offer 待遇不满意、业务不喜欢,应该相信自己,不要因为当下没有更好的 offer 而投降,一份工作短则一年长则 N 年,为了幸福生活要慎重选择!!!
    喜欢这篇文章文章的小伙伴们点赞+转发支持,你们的支持是我最大的动力!

//img-blog.csdnimg.cn/img_convert/6e0ba223f65e063db5b1b4b6aa26129a.png)

  • 框架原理真的深入某一部分具体的代码和实现方式时,要多注意到细节,不要只能写出一个框架。

  • 算法方面很薄弱的,最好多刷一刷,不然影响你的工资和成功率😯

  • 在投递简历之前,最好通过各种渠道找到公司内部的人,先提前了解业务,也可以帮助后期优秀 offer 的决策。

  • 要勇于说不,对于某些 offer 待遇不满意、业务不喜欢,应该相信自己,不要因为当下没有更好的 offer 而投降,一份工作短则一年长则 N 年,为了幸福生活要慎重选择!!!
    喜欢这篇文章文章的小伙伴们点赞+转发支持,你们的支持是我最大的动力!

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于 Spring Boot、WebSocketVue 实现后端向前端实时推送数据的代码示例: 1. 后端代码 ``` @Controller public class WebSocketController { private final WebSocketService webSocketService; @Autowired public WebSocketController(WebSocketService webSocketService) { this.webSocketService = webSocketService; } @GetMapping("/") public String index() { return "index"; } @MessageMapping("/send") public void send(String message) { webSocketService.sendAll(message); } @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } } ``` ``` @Service public class WebSocketService { private final List<Session> sessions = new CopyOnWriteArrayList<>(); public void add(Session session) { sessions.add(session); } public void remove(Session session) { sessions.remove(session); } public void sendAll(String message) { sessions.forEach(session -> { try { session.getBasicRemote().sendText(message); } catch (IOException e) { e.printStackTrace(); } }); } } ``` 2. 前端代码 ``` <template> <div> <h1>Real-time data:</h1> <ul> <li v-for="(data, index) in dataList" :key="index">{{ data }}</li> </ul> <input type="text" v-model="message" /> <button @click="send">Send</button> </div> </template> <script> export default { data() { return { dataList: [], message: '' } }, mounted() { const ws = new WebSocket('ws://localhost:8080/ws'); ws.onmessage = (event) => { this.dataList.push(event.data); }; ws.onclose = () => { console.log('Connection closed'); }; }, methods: { send() { const ws = new WebSocket('ws://localhost:8080/ws'); ws.onopen = () => { ws.send(this.message); ws.close(); }; } } } </script> ``` 在这个示例中,我们首先创建了一个 WebSocket 服务端,其中包含了一个用于处理客户端发送的消息的方法 send(),它会将接收到的消息发送给所有连接上的客户端。我们还创建了一个 WebSocketService,用于管理客户端连接和消息发送。 在前端,我们通过 Vue 的 mounted 生命周期创建了一个 WebSocket 连接,并在每次接收到服务器发来的消息时将其添加到一个数据列表中,然后在模板中通过 v-for 渲染出来。我们还在模板中添加了一个文本框和一个按钮,用于向服务器发送消息。当用户点击按钮时,我们创建一个新的 WebSocket 连接,并在连接打开后发送用户输入的消息,然后立即关闭连接。 要注意的是,我们在前端中创建了两个 WebSocket 连接,一个用于接收服务器推送的数据,另一个用于向服务器发送数据。这是因为 WebSocket 是全双工通信,可以同时进行发送和接收操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值