# 欢迎语

     // 客户端的代码
      // 1. 发送消息
      // 客户端 取input数据 -> websocket -> 发送到服务端 -> 转发给其他所有的客户端
      // 2. 显示消息
      var app = new Vue({
        el: "#app",
        data: {
          isShow: true,
          inputValue: "",
          items: [],
          wsHandle: "",
          name: "",
          num: 0,
        },
        // 把元素挂载完成之后,自动执行
        mounted() {
          var _this = this;
          this.wsHandle = new WebSocket("ws://localhost:8000");
          this.wsHandle.onopen = this.onOpen;
          // 服务端发送回来的其他消息
          this.wsHandle.onmessage = this.onMessage;
        },
        methods: {
          submit: function() {
            // 取inputValue
            // 通过websocket发送数据
            console.log(this.inputValue);
            this.wsHandle.send(
              JSON.stringify({
                name: this.name,
                message: this.inputValue,
              })
            );
            this.items.push({
              message: this.name + ": " + this.inputValue,
            });
            this.inputValue = "";
          },
          into: function() {
            if (this.name.trim() === "") {
              alert("用户名不得为空");
              return;
            }
            this.wsHandle.send(
              JSON.stringify({
                name: this.name,
              })
            );
            this.isShow = false;
          },
          onOpen: function() {
            console.log("client is connected");
          },
          onMessage: function(evt) {
            var msg = JSON.parse(evt.data);
            if (msg.num) {
              this.num = msg.num;
            }
            if (msg.name && !msg.message) {
              this.items.push({
                message: "欢迎" + msg.name + "加入聊天室!",
              });
            } else {
                // 把数据推送到items中
                this.items.push({
                  message: msg.name + ": " + msg.message,
                });
            }
          },
        },
      });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
上次更新: 2020/10/28 下午11:02:30