首页 > 解决方案 > 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;
    }
  });
},

标签: vue.js

解决方案


元素中没有内置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;
    }
  });
},

推荐阅读