socket功能集成聊天-发送空白文本

背景:

点击“提交”键,发送用户输入的文本。类似下图:

问题:

现在点击提交键,不仅文本显示不了在聊天记录上,并且,在发送函数方法中console.log打印输入框文本this.word,控制台出现的居然是空白的!

 解决思路:

1.怀疑是socket的问题,附上代码:

created () {
    this.socket = io('http://geek.itheima.net', {
      query: {
        token: getToken()
      },
      transports: ['websocket']
    })
    //   测试是否连接成功
    this.socket.on('connect', () => {
      console.log('连接成功啦!')
    })
    // 接收后端传回来的消息
    this.socket.on('message', obj => {
      // 理解组织相同字段对象放到数组里 -> v-for更新
      this.list.push({
        name: 'xs',
        msg: obj.msg
      })
    })
  },

2.但是因为socket能够正常打印出来成功文本,所以把问题定位到“提交”按钮的函数方法上:

methods: {
    sendFn () {
    //   if (this.word.trim().length === 0) return
      // 把消息发送给 websocket 服务器
      this.socket.emit('message', {
        msg: this.word,
        timestamp: new Date().getTime()
      })
      // 把消息显示到页面上
      this.list.push({
        msg: this.word,
        name: 'me'
      })
      //console.log('^^^', this.word)
      //console.log('###', this.list)
      // 清空输入框
      this.word = ''
    }
  },

 3.看了几十遍,都没有发现问题QAQ,百度也无果;最后还是看回自己的代码

4.最后定位在this.word上,既然data里的word输出是空白,那是不是漏写了双向绑定呢?

一看果然!!赶紧改正。

 总结:

想要跟小猫咪聊天,还是得多细心专心才行 TAT

 


版权声明:本文为weixin_56035334原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。