【问题标题】:Cannot read properties of undefined (reading 'toLowerCase')无法读取未定义的属性(读取“toLowerCase”)
【发布时间】:2021-11-28 05:47:23
【问题描述】:

我正在使用 Vue 创建一个搜索输入,并且我创建了一个方法来检查每个项目是否应该可见,并将当前用户输入与项目的数据进行比较,并返回 true 或 false。 我遇到的控制台问题,它显示了一个与“toLowerCase”相关的错误。 请提供一些帮助和建议。 提前致谢。

<div
  v-for="item in itemList"
  :key="item.name"
  class="dropdown-item"
  v-show="itemVisible(item)"
 />

export default {
  name: "Demo",
  data() {
    return {
      inputValue: "",
      itemList: [],
      selectedItem: {},
    };
  },
itemVisible(item) {
  let currentName = item.name.toLowerCase();
  let currentInput = this.inputValue.toLowerCase();
  return currentName.includes(currentInput);
 }
}

【问题讨论】:

    标签: vue.js vuejs2 vue-options-api


    【解决方案1】:

    看起来 itemVisible(item) 函数应该放在 methods 对象中,但事件可能不会像您预期的那样工作,因为它只会在初始渲染时执行一次。

    您可能想要watch inputValue 参数,然后对selectedItems 的每个项目执行itemVisible() 方法,并将有关可见性的数据直接保存到项目或并行数据结构中。

    【讨论】:

      【解决方案2】:

      我会做这样的事情。

      <template>
          <ul v-for="(item, idx) in itemList" :key="`key-${idx}`">
              <li class="dropdown-item" v-show="itemVisible(item)">
                  {{ item.name }}
              </li>
          </ul>
      </template>
      <script>
      export default {
          name: "Demo",
      
          data() {
              return {
                  inputValue: "i",
                  itemList: [
                      { name: 'hi' },
                      { name: 'by' },
                  ],
                  selectedItem: {},
              };
          },
      
          methods() {
              itemVisible(item) {
                  let currentName  = item.name.toLowerCase();
                  let currentInput = this.inputValue.toLowerCase();
                  return currentName.includes(currentInput);
              }
          }
      }
      </script>
      

      如果你不想要 ul/li,你可以用模板交换 ul,用 div 交换 li

      <template ...loop... > <div class="..."> {{ item.name }} </div> </template>
      

      【讨论】:

        猜你喜欢
        • 2020-07-23
        • 2020-06-24
        • 2018-10-23
        • 2021-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-12
        • 2021-03-15
        相关资源
        最近更新 更多