vue.js - VUE,有时我在点击功能上得到未定义的值
问题描述
我有一个元素列表,在 v-for 上创建并将值绑定到和 id。当我单击时,我使用该值来做事。问题是有时值是“未定义的”。其他时候不是。如果是“未定义”,我单击上面的列表项,然后返回“未定义”,我得到正确的值。这是怎么回事?:key 分配给数据中的唯一 id (index+1)
<template
v-if="filteredContacts.length > 0 || searchToggle == true"
>
<li
@click="selectContact($event)"
v-for="(contact, index) in filteredContacts "
:value="contact.id"
:key="contact.id"
>
<div class="logo">
<img :src="contact.avatar" alt="LOGO" />
</div>
<span class="contact-name">{{contact.name}}</span>
<div class="last-message">
Here will stay the last message
</div>
</li>
在 v-for 之上,函数之下:
selectContact(event) {
let value = event.target.value;
console.log(value);
this.contacts.forEach((e) => {
if (e.id == value) {
this.currentContact = e;
}
});
},
解决方案
元素中没有内置value
属性li
,在您的情况下,您应该直接通过参数传递 id :
<template
v-if="filteredContacts.length > 0 || searchToggle == true"
>
<li
v-for="(contact, index) in filteredContacts "
@click="selectContact(contact.id)"
:key="contact.id"
>
<div class="logo">
<img :src="contact.avatar" alt="LOGO" />
</div>
<span class="contact-name">{{contact.name}}</span>
<div class="last-message">
Here will stay the last message
</div>
</li>
selectContact(id) {
this.contacts.forEach((e) => {
if (e.id == id) {
this.currentContact = e;
}
});
},
推荐阅读
- laravel - 导入excel并插入数据库
- json - 如何将正确的键和值从 jq 拉到 bash shell 脚本中的数组中
- swift - CFAttributedString 改变字体大小没有效果
- android - FCM 通知在一段时间后未到达
- javascript - 在 React 中将 JSON 复制到地图中
- c# - ASP.NET Core 3.0 将身份用户分配给自定义模型
- azure-data-lake - 如何用空值连接字符串
- delphi - Delphi中如何正确使用IFileOperation删除文件夹中的文件
- javascript - 根据用户复选框创建 api 输入参数
- flutter - Dart HttpClient 未读取完整响应