【问题标题】:How do we display the data got from axios in a table in Vuejs?我们如何在 Vuejs 的表格中显示从 axios 获得的数据?
【发布时间】:2020-09-24 02:01:57
【问题描述】:

我是 Vuejs 新手,在使用 axios 显示从 API 端点检索到的数据/用户信息时遇到了一个问题。以下是从 api 端点检索数据的代码:

import axios from 'axios';

export default {

  data(){
        return{
            userInfo: []
        };
    },

  created(){
      this.getInfo();
  },

  methods:{
    getInfo(){
        axios.get('http://URL')
        .then(response => this.userInfo = response.data)
        .catch(error => this.userInfo = error.data);
    },      
  }  
}

所以,我确实将来自 api 端点的数据放入 userInfo(这是一个数组 - 用户名、userId 等)。如何在 vuejs 的模板部分的表格形式中显示 userInfo(这是一个数组)的内容?

如果下面是我在 vuejs 的模板(html 部分)中创建的表的架构?如何使用从 api 端点获取的 userInfo 中的数据填充行?

<el-table>
  <el-table-column min-width="50" type="index"></el-table-column>
  <el-table-column min-width="150" label="Name"></el-table-column>
</el-table>

上面的代码只是简单地创建了一个列,但是我如何使用从 userInfo 中获取的数据来填充它呢? UserInfo 具有用户的用户名。我想用 userInfo 中的用户名填充“名称”列的行。

我可以使用以下代码在 UI 上将用户名显示为用户名列表:

<ul id="dsiplaying">
    <li v-for="user in userInfo" :key="userInfo.id">{{user.username}}
</li></ul>

但是,如何将用户名填充到上面创建的名称列中?

任何帮助将不胜感激。

【问题讨论】:

  • &lt;el-table&gt; 来自哪里?那是 ElementUI 还是其他什么?如果是 Element,您是否尝试过查看 documentation 中的示例?

标签: vue.js axios element-ui


【解决方案1】:

在我看来,元素 UI 非常难以使用,因为它过于繁琐 documentation 但如果你必须...

<el-table :data="userInfo"> <!-- ? bind the table's "data" prop to your "userInfo" array -->

  <!-- this is an index column, ie row number starting from "1" -->
  <el-table-column type="index" min-width="50"></el-table-column>

  <!-- this column shows the "id" property of your objects -->
  <el-table-column prop="id" label="ID"></el-table-column>

  <!-- this column shows the "username" property of your objects -->
  <el-table-column prop="username" label="Username"></el-table-column>
</el-table>

当您的 userInfo 数组为空时,这最初不会呈现任何内容,但一旦 Axios 请求完成并更新您的数组,表格将填充数据。


如果你只是想在一个普通的旧 HTML 表格中显示你的数据,你会使用这样的东西

<table>
  <thead>
    <tr>
      <th></th>
      <th>ID</th>
      <th>Username</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(user, index) in userInfo" :key="user.id">
      <td>{{ index + 1 }}</td>
      <td>{{ user.id }}</td>
      <td>{{ user.username }}</td>
    </tr>
  </tbody>
</table>

【讨论】:

  • 非常感谢。上面的代码对我来说很顺利。
猜你喜欢
  • 1970-01-01
  • 2021-07-24
  • 2019-01-08
  • 1970-01-01
  • 2019-08-02
  • 2020-02-12
  • 2019-11-03
  • 1970-01-01
  • 2017-11-08
相关资源
最近更新 更多