简体   繁体   English

将 socket.io(客户端)JSON 传递给 Vue.js 组件

[英]Pass socket.io (client) JSON to Vue.js Component

Similar to this question here I'm trying to pass socket.io-client data to a Vue.js component but it's not displaying on the page -- though it writes to console.log just fine.类似于这里的这个问题我试图将 socket.io-client 数据传递给 Vue.js 组件,但它没有显示在页面上——尽管它写入 console.log 就好了。 My data is JSON (his was an array) so the solution in the link above doesn't seem to work.我的数据是 JSON(他是一个数组),所以上面链接中的解决方案似乎不起作用。

The error I'm getting is:我得到的错误是:
[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>

sample data样本数据

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

Any help would be greatly appreciated.任何帮助将不胜感激。 Thanks.谢谢。

the data attribute in your vue instance needs to be a function which returns something, your items array for instance.你的 vue 实例中的data属性需要是一个返回一些东西的函数,例如你的items数组。 so instead of所以而不是

    data: {
      items: []
     },

you should re-write as你应该重写为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM