【发布时间】:2020-04-16 16:22:26
【问题描述】:
编辑:可以在这里找到类似但略有不同的问题:Vue.js : How to set a unique ID for each component instance?
我正在尝试创建一个表格,以便有人可以检查他们想要添加到组中的人。到目前为止,我已经设法使用 PHP 从数据库中检索它们,并使用 HTML 中的 vue 显示它们。现在我想为每个复选框 ID 分配学生的电子邮件,以便稍后将选中的学生发送回 PHP。可能有(很多)更好的方法可以做到这一点,但我对此很陌生。
这是我当前的输出: My Output
我的 HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="vue-app">
<table>
<thead>
<tr>
<th>Select</th>
<th>Firstname</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr v-for="(student, index) in students">
<input type="checkbox" id="{{student.email}}">
<td>{{student.firstname}}</td>
<td>{{student.lastname}}</td>
</tr>
</tbody>
</table>
</div>
var app = new Vue({
el: '#vue-app',
data: {
students: []
},
mounted: function () {
axios.get('get_students_list.php')
.then(response => {
this.students = response.data;
console.log(students);
})
.catch(error => {
console.log(error);
});
}
})
get_students_list.php:
try {
include("db_connection.php");
$isteacher = false;
$query = "SELECT firstname, lastname, email FROM persons WHERE isteacher = :isteacher";
$statement = $conn->prepare($query);
$statement->bindParam(':isteacher', $isteacher);
$statement->execute();
//gets row as associative array
$users = $statement->fetchAll(PDO::FETCH_ASSOC);
$students = json_encode($users);
echo $students;
} catch (PDOException $error) {
echo $error;
}
我已经尝试了上述 id 分配,还尝试使用以下代码使用 javascript 创建一个复选框(这也不起作用,因为我无法从那里访问 vue 元素):
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.id = {{student.email}};
checkbox.checked = false;
其他尝试:
<input type="checkbox" v-bind:id="student.email">
和
<input type="checkbox" :id="student.email">
【问题讨论】:
-
如下面答案中所写,需要使用 v-bind 绑定 id 属性。简单地使用 id="{{...}}" 不会插入模板变量,而是逐字插入。
-
是的,但是上面提到的代码也不起作用。我尝试了 v-bind:id 和 :id 但两者都在我的代码中抛出错误。
-
不要在属性中使用 {{...}},请参阅下面的文档链接。
-
对不起,我忘了把它从帖子里拿出来,反正我的代码里已经没有了。
-
此外,不断编辑问题会使读者很难看到发生了什么;而是将您已经尝试过的内容添加到您的问题中,以便其他人可以效仿。
标签: javascript vue.js checkbox dynamic html-table