1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

plunkerでvue その48

Last updated at Posted at 2021-06-05

概要

plunkerでvueやってみた。
練習問題、やってみた。

練習問題

chatを実装せよ。

参考にしたページ

バックエンド

enebular

サンプルコード

const MSG_START = "start";

new Vue({
  el: "#app",
  components: {},
  data: () => ({
    name: "名無し",
    message: "おはようございます。",
    connection: null,
    messages: [],
    ws_key: 0,
    avatar_color: "",
  }),
  created: function() {
    this.connection = new WebSocket("wss://ohiapp0.herokuapp.com/pub");
    let random_color = "#";
    for (var i = 0; i < 6; i++) 
    {
      random_color += "0123456789abcdef"[(16 * Math.random()) | 0];
    }
    this.avatar_color = random_color;
    const vm = this;
    this.connection.onopen = function() {
      vm.sendMessageData(vm.avatar_color, MSG_START, vm.name);
    };
    this.connection.onmessage = function(event) {
      const msg_json = JSON.parse(event.data);
      vm.messages.push({
        ws_key: 1,
        avatar_color: msg_json.avatar_color,
        message: msg_json.message,
        name: msg_json.name,
      });
    };
  },
  updated: function() {
    this.scrollToEnd();
  },
  methods: {
    send_onClick: function() {
      if (this.message == "") 
        return;
      this.sendMessageData(this.avatar_color, this.message, this.name);
      this.message = "";
    },
    sendMessageData: function(avatar_color, message, name) {
      const msg_json = {
        avatar_color,
        message,
        name,
      };
      this.connection.send(JSON.stringify(msg_json));
    },
    scrollToEnd() {
      this.$nextTick(() => {
        const chatLog = this.$refs.scrollTarget;
        if (!chatLog) 
          return;
        chatLog.scrollTop = chatLog.scrollHeight;
      });
    },
  },
})




成果物

以上。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?