【问题标题】:Populate HTML table with Vue 3使用 Vue 3 填充 HTML 表格
【发布时间】:2021-03-14 04:46:40
【问题描述】:

我想用从 API 返回的数据填充表格。现在,该表没有显示任何数据,但我正在检索并查看我的 console.log 中的数据。我是否错误地将数据调用到我的表中?

<template>
  <div>
    <table>
      <tr>
        <th>S/N</th>
        <th>Username</th>
        <th>Email</th>
        <th>Group Role</th>
      </tr>
      <tr>
        <td><div></div></td>
        <td><div contenteditable>{{users}}</div></td>
        <td><div contenteditable>{{email}}</div></td>
        <td><div contenteditable>{{role}}</div></td>
      </tr>

    </table>
  </div>
</template>
import { onMounted, ref, reactive } from 'vue'

export default {
  name: 'manage-users-edit',

  setup(){
    const users = ref(null);
    const email = ref(null);
    const role = ref(null);
    const API_URL = '';

    async function getData() {
      const response = await fetch(API_URL);
      const data = await response.json();
      for(let i=0; i<=data.length; i++){
        users[i] = data[i].userName;
        email[i] = data[i].emailAddress;
        role[i] = data[i].userType;
        console.log('users', users[i]);
        console.log('email', email[i]);
        console.log('role', role[i]);
      }
    }

    onMounted(async () => {
      console.log('Dashboard mounted!')
      getData();
    })
  }
}

【问题讨论】:

    标签: javascript html vue.js vue-component vuejs3


    【解决方案1】:

    为什么不使用v-for 指令。 我会为你做以下事情:

    ...
    setup(){
        let listUser = [] // It is better to go on a let since we will reassign the API data to the variable
        const API_URL = '';
    
        async function getData() {
           const response = await fetch(API_URL);
           const data = await response.json();
           this.listUser = data
           console.log('data-users', this.listUser);
      }
    }
    ...
    }
    

    然后在模板级别,我们使用v-for指令浏览listUser中记录的所有数据:

      ...
      <tr v-for="item in listUser">
        <td><div></div></td>
        <td><div contenteditable>{{item.users}}</div></td>
        <td><div contenteditable>{{item.email}}</div></td>
        <td><div contenteditable>{{item.role}}</div></td>
      </tr>
      ...
    

    【讨论】:

      【解决方案2】:

      您需要从setup 返回模板将使用的任何数据。使用属性名称与模板的变量名称匹配的对象:

      setup() {
        ...
        return {
          users,
          email,
          role
        }
      }
      

      这相当于:

      setup() {
        ...
        return {
          users: users,
          email: email,
          role: role
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-12
        • 2016-03-03
        • 1970-01-01
        • 1970-01-01
        • 2011-03-15
        • 1970-01-01
        相关资源
        最近更新 更多