【问题标题】:Pass socket.io (client) JSON to Vue.js Component将 socket.io(客户端)JSON 传递给 Vue.js 组件
【发布时间】:2018-08-13 23:26:56
【问题描述】:

类似于这个问题here 我正在尝试将socket.io-client 数据传递给Vue.js 组件,但它没有显示在页面上——尽管它写入console.log 就好了。我的数据是 JSON(他是一个数组),所以上面链接中的解决方案似乎不起作用。

我得到的错误是:
[Vue warn]: Property or method "items" is not defined on the instance but referenced during render.

main.js

import Vue from 'vue'
import App from './App'
import io from 'socket.io-client'

Vue.config.productionTip = false
var socket = io.connect('http://localhost:3000')

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>',
  data: {
    items: []
  },
  mounted: function () {
    socket.on('connect', function () {
      socket.on('message', function (message) {
        console.log(message)
        this.items = message.content
      }.bind(this))
      socket.emit('subscribe', 'mu')
    })
  }
})

App.vue

<template>
  <div id="app">
    <h1>client</h1>
    <div v-for="item in items" class="card">
      <div class="card-block">
        <h4 class="card-title">Symbol: {{ item.symbol }}</h4>
        <p class="card-text">Updated: {{ item.lastUpdated }}</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

样本数据

{  
   "symbol":"MU",
   "lastUpdated":1520283600000
}

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: javascript node.js vue.js socket.io


    【解决方案1】:

    您的 vue 实例中的 data 属性需要是一个返回某些内容的函数,例如您的 items 数组。所以而不是

        data: {
          items: []
         },
    

    你应该改写成

    data () {
      return {
        items: []
      }
     },
    

    【讨论】:

      猜你喜欢
      • 2016-01-10
      • 2012-09-10
      • 1970-01-01
      • 2013-02-21
      • 2017-09-11
      • 2016-06-15
      • 1970-01-01
      • 2018-04-29
      相关资源
      最近更新 更多