首页 > 解决方案 > 如何为li list vue js获取加载更多按钮

问题描述

我正在尝试在我的代码中实现一个加载更多按钮。我可以在 javascript 中做到这一点,但在 vue 中找不到类似的方式。这是我的 Vue 代码。我试过用公司 ID 询问元素,但它不是反应性的,所以我不能只改变样式。

<main>

    <ul>
      <li v-for="company in companiesdb" :key="company.id" v-bind:id="company.id"  ref="{{company.id}}" style="display: none">
        {{company.name}}<br>
        {{company.email}}
      </li>

    </ul>

</main>

这是我在 javascript 中失败的尝试,但正如我之前提到的 ref 不是反应性的,所以我不能这样做

limitView: function (){
   const step = 3;
   do{
     this.numberCompaniesVis ++;
     let li = this.$refs[this.numberCompaniesVis];
     li.style = "display: block";
   }while (this.numberCompaniesVis % 3 != step)
}

标签: javascriptvue.js

解决方案


我认为你处理这个问题的方式有点复杂。相反,您可以创建一个计算变量来更改显示的列表数量。

这是代码

<template>
  <div id="app">
    <ul>
      <li v-for="(company, index) in companiesLoaded" :key="index">
        {{ company }}
      </li>
    </ul>
    <button @click="loadMore">Load</button>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      companiesdb: [3, 4, 1, 4, 1, 2, 4, 4, 1],
      length: 5,
    };
  },
  methods: {
    loadMore() {
      if (this.length > this.companiesdb.length) return;
      this.length = this.length + 3;
    },
  },
  computed: {
    companiesLoaded() {
      return this.companiesdb.slice(0, this.length);
    },
  },
};
</script>

因此,与其从 companydb 加载列表,不如创建一个计算函数,该函数将基于 Companiesdb 变量返回新数组。然后是每次用户单击按钮时都会执行的 loadMore 函数。此函数将增加初始长度,因此将显示更多列表。

这是现场示例


推荐阅读