【问题标题】:I can't display data in a table with vue我无法使用 vue 在表格中显示数据
【发布时间】:2020-03-24 18:44:58
【问题描述】:

我正在尝试通过 vuejs 在表格中显示数据,但它会引发以下错误。 [Vue 警告]:渲染错误:“TypeError:无法读取属性 'id' of null”

export default {
    created: function() {
        this.getCiudades();
    },
    data() {
      return {
        ciudades: [],
      }
    },
    methods: {
        getCiudades: function() {
            var urlciudades = 'ciudadesjson';
            axios.get(urlciudades).then(response => {
                this.ciudades = response.data;
                });
            }
    }
}

<tbody>
  <tr v-for="ciudad in ciudades" v-bind:key="ciudad.id">
    <td>
      @{{ ciudad.id }}
    </td>
    <td>
      @{{ ciudad.nombres }}
    </td>
  </tr>
</tbody>

【问题讨论】:

  • 似乎至少有一项是null。把ciudad.id改成ciudad,评论ciudad.nombres看看有没有这个项目。
  • 查看浏览器的 Network 控制台以检查从服务器返回的响应。
  • 请检查网络并在此处添加axios 回复。

标签: vue.js


【解决方案1】:

也许这会有所帮助

                <tbody>
                <tr v-for="(ciudad,i) in ciudades" :key="i">
                    <td>
                        @{{ ciudad.id }}
                    </td>
                    <td>
                        @{{ ciudad.nombres }}
                    </td>
                </tr>
            </tbody>

如果 ciudad.id 在数组中的任何对象中为空,则可以使用索引号作为键,或 ciucad.id。

【讨论】:

    【解决方案2】:

    如果您确定您的method/function 通过console.log-ing 收到您的回复,您的数据如下:

    methods: {
      getCiudades() {
        var urlciudades = 'ciudadesjson';
        axios.get(urlciudades).then(response => {
          this.ciudades = response.data;
          console.log('myData:', response.data)
        });
      }
    }
    

    那么简单的解决方案是将v-if添加到table

    <table v-if='ciudades.length'>...</table>
    

    或使用占位符键和值启动您的数据

    data() {
      return {
        ciudades: [
          {
            id: 0,
            nombres: '',
          },
        ],
      };
    },
    

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多