Bladeren bron

update MessageStream

reghao 1 jaar geleden
bovenliggende
commit
ec65bf7851
4 gewijzigde bestanden met toevoegingen van 52 en 229 verwijderingen
  1. 1 1
      src/router/index.js
  2. 50 23
      src/views/home/MessageStream.vue
  3. 0 204
      src/views/home/MessageStream1.vue
  4. 1 1
      src/views/home/MessageStream2.vue

+ 1 - 1
src/router/index.js

@@ -25,7 +25,7 @@ const ImageIndex = () => import('views/home/Image')
 const ImagePage = () => import('views/home/ImagePage')
 const ArticleIndex = () => import('views/home/Article')
 const ArticlePage = () => import('views/home/ArticlePage')
-const MessageStream = () => import('views/home/MessageStream2')
+const MessageStream = () => import('views/home/MessageStream')
 const Search = () => import('views/home/Search')
 const DiscoverIndex = () => import('views/home/Discover')
 

+ 50 - 23
src/views/home/MessageStream.vue

@@ -3,7 +3,7 @@
     <el-col :md="18">
       <div class="movie-list" style="height: 70vh;">
         <!-- 注意需要给 el-scrollbar 设置高度,判断是否滚动是看它的height判断的 -->
-        <el-scrollbar style="width: 100%; height: 100%;">
+        <el-scrollbar ref="myScrollbar" style="width: 100%; height: 100%;">
           <el-row class="movie-list">
             <div
               v-for="(item, index) in dataList"
@@ -12,18 +12,21 @@
               :sm="12"
               :xs="12"
             >
-              <el-row style="padding-right: 5px; padding-left: 5px; padding-bottom: 5px">
-                <el-card class="box-card">
-                  <el-row>
-                    <el-col :md="20">
-                      <el-row>
-                        <div style="padding: 14px">
-                          <span style="left: 0;margin-bottom: 0px;color: black;">{{ item.content }}</span>
-                        </div>
-                      </el-row>
-                    </el-col>
-                  </el-row>
-                </el-card>
+              <el-row
+                style="padding-right: 5px; padding-left: 5px; padding-bottom: 5px"
+                type="flex"
+                class="row-bg"
+                :justify="item.justify"
+              >
+                <el-col :md="12">
+                  <el-card class="box-card">
+                    <el-row>
+                      <div style="padding: 14px">
+                        <span style="right: 0;margin-bottom: 0px;color: black;">{{ item.content }}</span>
+                      </div>
+                    </el-row>
+                  </el-card>
+                </el-col>
               </el-row>
             </div>
           </el-row>
@@ -64,8 +67,10 @@
 </template>
 
 <script>
+import { getAccessToken } from '@/utils/auth'
+
 export default {
-  name: 'MessageStream',
+  name: 'WebSocket',
   filters: {
     ellipsis(value) {
       if (!value) return ''
@@ -80,11 +85,18 @@ export default {
     return {
       dataList: [],
       text: '',
-      websocket: null
+      websocket: null,
+      token: null
     }
   },
   created() {
     document.title = 'MessageStream'
+    const token = getAccessToken()
+    if (token === null) {
+      this.token = '1234567890'
+    } else {
+      this.token = token
+    }
     this.initWebSocket()
   },
   methods: {
@@ -92,15 +104,11 @@ export default {
       this.dataList = []
     },
     onSubmit() {
-      this.$notify({
-        message: this.text,
-        type: 'info',
-        duration: 1000
-      })
+      this.websocketSend(this.text)
       this.text = ''
     },
     initWebSocket: function() {
-      var url = 'wss:' + process.env.VUE_APP_SERVER_URL + '/ws/log?token=1234567890'
+      var url = 'ws:' + process.env.VUE_APP_SERVER_URL + '/ws/message?token=' + this.token
       this.websock = new WebSocket(url)
       this.websock.onopen = this.websocketOnopen
       this.websock.onerror = this.websocketOnerror
@@ -118,8 +126,18 @@ export default {
     },
     websocketOnmessage: function(e) {
       const evtData = JSON.parse(e.data)
+      const receiverId = evtData.receiverId
+      const senderId = evtData.senderId
       const payload = evtData.payload
-      this.dataList.push(payload)
+      var justify = 'start'
+      if (senderId === this.token) {
+        justify = 'end'
+      }
+
+      this.dataList.push({
+        content: payload,
+        justify: justify
+      })
     },
     websocketOnclose: function(e) {
       console.log('connection closed (' + e.code + ')')
@@ -128,8 +146,9 @@ export default {
     websocketSend(text) { // 数据发送
       try {
         this.websock.send(text)
+        this.$message.success('消息已发送')
       } catch (err) {
-        console.log('send failed (' + err.code + ')')
+        this.$message.error('send failed (' + err.code + ')')
       }
     },
     reconnect() {
@@ -162,4 +181,12 @@ export default {
   padding-left: 6%;
   padding-right: 6%;
 }
+
+/*必要的*/
+/*隐藏底部滚动条*/
+  /deep/ .el-scrollbar__wrap {
+    overflow: scroll;
+    height: 100% !important;
+    overflow-x: hidden !important;
+  }
 </style>

+ 0 - 204
src/views/home/MessageStream1.vue

@@ -1,204 +0,0 @@
-<template>
-  <el-row class="movie-list">
-    <el-col :md="18">
-      <div class="movie-list" style="height: 70vh;">
-        <el-scrollbar style="width: 100%; height: 100%;">
-          <div ref="comment" :style="wrapStyle" class="comment-wrap">
-            <comment
-              v-model="videoComments"
-              :user="currentUser"
-              :props="props"
-              :before-submit="submit"
-              :before-like="like"
-              :before-delete="deleteComment"
-              :upload-img="uploadImg"
-            />
-          </div>
-        </el-scrollbar>
-      </div>
-    </el-col>
-    <el-col :md="6">
-      <el-row style="padding-right: 5px; padding-left: 5px; padding-bottom: 5px">
-        <el-col>
-          <el-button
-            size="mini"
-            type="danger"
-            class="el-icon-delete"
-            @click="clear"
-          >清空</el-button>
-        </el-col>
-      </el-row>
-      <el-row style="padding-right: 5px; padding-left: 5px; padding-bottom: 5px">
-        <el-card class="box-card">
-          <el-input
-            v-model="text"
-            type="textarea"
-            :rows="3"
-            placeholder="有什么新鲜事想分享给大家?"
-          />
-          <el-row style="text-align: right">
-            <el-button
-              size="mini"
-              type="submit"
-              class="el-icon-message"
-              @click="onSubmit"
-            >发送</el-button>
-          </el-row>
-        </el-card>
-      </el-row>
-    </el-col>
-  </el-row>
-</template>
-
-<script>
-import comment from '@/components/comment'
-
-export default {
-  name: 'MessageStream1',
-  components: { comment },
-  data() {
-    return {
-      wrapStyle: '',
-      videoComments: [],
-      currentUser: {
-        userId: 1,
-        name: '草莓',
-        avatar: '//picx.zhimg.com/v2-a2c89378a6332cbfed3e28b5ab84feb7.jpg',
-        author: true
-      },
-      props: {
-        id: 'id',
-        content: 'content',
-        imgSrc: 'imgSrc',
-        children: 'children',
-        likes: 'likes',
-        liked: 'liked',
-        reply: 'reply',
-        createAt: 'createAt',
-        user: 'user'
-      },
-      text: '',
-      dataList: []
-    }
-  },
-  created() {
-    document.title = 'WebSocket'
-    this.initWebSocket()
-  },
-  methods: {
-    async submit(newComment, parent, add) {
-      const res = await new Promise((resolve) => {
-        setTimeout(() => {
-          resolve({ newComment, parent })
-        }, 300)
-      })
-      add(Object.assign(res.newComment, { _id: new Date().getTime() }))
-      console.log('addComment: ', res)
-    },
-    async like(comment) {
-      const res = await new Promise((resolve) => {
-        setTimeout(() => {
-          resolve(comment)
-        }, 0)
-      })
-
-      console.log('likeComment: ', res)
-    },
-    async uploadImg({ file, callback }) {
-      const res = await new Promise((resolve, reject) => {
-        const reader = new FileReader()
-        reader.readAsDataURL(file)
-        reader.onload = () => {
-          resolve(reader.result)
-        }
-        reader.onerror = () => {
-          reject(reader.error)
-        }
-      })
-      callback(res)
-      console.log('uploadImg: ', res)
-    },
-    async deleteComment(comment, parent) {
-      const res = await new Promise((resolve) => {
-        setTimeout(() => {
-          resolve({ comment, parent })
-        }, 300)
-      })
-      console.log('deleteComment: ', res)
-    },
-    clear() {
-      this.dataList = []
-    },
-    onSubmit() {
-      this.$notify({
-        message: this.text,
-        type: 'info',
-        duration: 1000
-      })
-      this.text = ''
-    },
-    initWebSocket: function() {
-      var url = 'wss:' + process.env.VUE_APP_SERVER_URL + '/ws/message?token=11011'
-      this.websock = new WebSocket(url)
-      this.websock.onopen = this.websocketOnopen
-      this.websock.onerror = this.websocketOnerror
-      this.websock.onmessage = this.websocketOnmessage
-      this.websock.onclose = this.websocketOnclose
-    },
-    websocketOnopen: function() {
-      console.log('WebSocket连接成功')
-      // 心跳检测重置
-      // this.heartCheck.reset().start();
-    },
-    websocketOnerror: function(e) {
-      console.log('WebSocket连接发生错误')
-      this.reconnect()
-    },
-    websocketOnmessage: function(e) {
-      const evtData = JSON.parse(e.data)
-      console.log(evtData)
-      // this.dataList.push(payload)
-      this.videoComments.push(evtData)
-    },
-    websocketOnclose: function(e) {
-      console.log('connection closed (' + e.code + ')')
-      this.reconnect()
-    },
-    websocketSend(text) { // 数据发送
-      try {
-        this.websock.send(text)
-      } catch (err) {
-        console.log('send failed (' + err.code + ')')
-      }
-    },
-    reconnect() {
-      var that = this
-      if (that.lockReconnect) return
-      that.lockReconnect = true
-      // 没连接上会一直重连,设置延迟避免请求过多
-      setTimeout(function() {
-        console.info('尝试重连...')
-        that.initWebSocket()
-        that.lockReconnect = false
-      }, 5000)
-    }
-  }
-}
-</script>
-
-<style scoped>
-/*处于手机屏幕时*/
-@media screen and (max-width: 768px) {
-  .movie-list {
-    padding-top: 8px;
-    padding-left: 0.5%;
-    padding-right: 0.5%;
-  }
-}
-
-.movie-list {
-  padding-top: 15px;
-  padding-left: 6%;
-  padding-right: 6%;
-}
-</style>

+ 1 - 1
src/views/home/MessageStream2.vue

@@ -85,7 +85,7 @@ export default {
   },
   created() {
     document.title = 'EventSource'
-    // this.init()
+    this.init()
   },
   methods: {
     clear() {