【发布时间】:2019-06-17 09:09:16
【问题描述】:
我正在尝试用 axios 和 vue 填充表格,如下所示:
<div class="container h-100">
<div class="row h-100 justify-content-center align-items-center">
<table class="table table-striped table-bordered table-hover">
<thead class="thead-dark">
<tr>
<th>#</th>
<th>First</th>
<th>Last</th>
<th>Handle</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users">
<td>{{user.name}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
<td>{{user.phone}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var users;
axios.get('https://jsonplaceholder.typicode.com/users')
.then(function (response) {
users = response['data'];
})
.catch(function (error) {
console.log(error);
})
</script>
问题是 {{user.name}} 返回 '{{user.name}}' ,不显示真实数据。有人知道如何使用 vue 在表格中显示数组数据吗?
更新
我使用此代码进行了更新,但视图仍然为空。如果我在脚本中返回 this.users,则返回一个带有值的对象。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Tabla</title>
<style>
body,
html {
height: 100%;
}
</style>
</head>
<body>
<div id="tabla">
<div class="container h-100">
<div class="row h-100 justify-content-center align-items-center">
<table class="table table-striped table-bordered table-hover text-center">
<thead class="thead-dark">
<tr>
<th>Name</th>
<th>Username</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users">
<td>{{user.name}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
<td>{{user.phone}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: '#tabla',
data: {
users: [],
},
created: function () {
this.load();
},
methods: {
load: function () {
axios
.get('https://jsonplaceholder.typicode.com/users')
.then(function (response) {
this.users = response.data;
})
.catch(function (error) {
console.log(error);
})
}
}
})
</script>
</html>
【问题讨论】:
-
这不像vue组件?我们可以得到一个可运行的 sn-p 吗?