【问题标题】:How can I iterate over array data and create new row for every new data in vue?如何遍历数组数据并为 vue 中的每个新数据创建新行?
【发布时间】:2019-09-20 12:47:52
【问题描述】:

我有一个通过axios.get 调用的流数据,resposne.data 是一个带有一个传感器数据的json,例如,{"Temperature":"56"},,我用它在vue 模板中创建一行。resposne.data 分配给数组但它没有附加行,表中的数据正在改变。

这是模板部分

<template>
  <div class="container">
      <h1>Tabular Data</h1>
      <table class="table table-striped table-bordered" >
          <thead>
              <tr>

                  <th class="text-center">Time</th>
                  <th class="center">Device Parameter</th>
                  <th class="center">Magnitude</th>
                  <th class="right">Unit</th>     
              </tr>
          </thead>

          <tbody>


                  <tr v-for="data in Tabular" :key="data">
                    <td> {{new Date().toString()}} </td>
                    <td class="test-left">Temperature</td>
                    <td class="text-center"> {{data.toString()}} </td>
                    <td class="test-left">C</td> 

                  </tr>

                  <!-- <td>{{data_alias.Humidity}}</td>
                  <td>{{data_alias.Pressure}}</td> -->  

          </tbody>

      </table>

  </div>
</template>

<script>
/* eslint-disable */
import axios from 'axios';
export default {

    name: 'tabular',
    data() {

        return {
            Tabular:[ ],

        }
    },


    mounted() {
        setInterval(()=>{
        axios.get('http://localhost:3000/data')
            .then((response)=>{
            console.log(response.data);
            this.Tabular=response.data; 

        })
        .catch((error)=>{
            console.log(error);
        });

    },2000);//I used set interval to get data from stream constantly
 },

}
</script>

【问题讨论】:

  • 看起来您并没有将新获取的值添加到数组中,而是使用this.Tabular=response.data; 更改每次获取数据时的完整数组。您需要添加到数组中,而不是相等。
  • 是的,我明白了,谢谢@mcy

标签: vue.js


【解决方案1】:

你确定Tabular 是一个偶数吗? 我认为没有,因为this.Tabular=response.data; ;

this.Tabular 是 undefined ;

试试这个

var that = this;
axios.get('http://localhost:3000/data')
            .then((response)=>{
            console.log(response.data);
            that.Tabular=response.data; 

        })
        .catch((error)=>{
            console.log(error);
        });

【讨论】:

  • 他正在使用箭头功能,所以他可以访问this
【解决方案2】:

那是因为你要替换this.Tabular 的内容。您应该遍历您的响应数据,并且考虑到 response.data 是一个行数组,请使用

response.data.forEach((row) => { this.Tabular.push(row) })

【讨论】:

    猜你喜欢
    • 2019-12-16
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    • 2023-02-04
    • 2017-05-08
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多