【问题标题】:How to push elements to computed property in Vue?如何将元素推送到 Vue 中的计算属性?
【发布时间】:2022-12-05 19:35:04
【问题描述】:

我正在 Vue3 应用程序中构建无限滚动功能。一切正常,除了当用户滚动到页面末尾时我找不到推送更多数据的方法。

所有配置文件最初都加载到 Vuex 中,但随着用户不断向下滚动,只能逐批渲染。

我想首先呈现初始数量的个人资料,而不是在用户到达页面底部后将一些新的个人资料推送到保存数组的数据中。

我最初需要使用计算属性,因为这将等到配置文件的 Vuex 数组从数据库加载完毕。如果我使用钩子,风险是数据尚未加载。此外,每次添加新数据时,计算属性都会重新计算。

所以 v-for 指令绑定到这个计算属性。

但是我如何将新的配置文件推送到这个计算属性?我试图将此计算属性分配给组件数据属性,但这显然不是它的工作方式。

非常感谢任何帮助。

<template>
  <div v-for="profile in loadedProfiles" :key="profile.id">
    {{ profile.name }}
  </div>
</template>

<script>
export default {

  data: () => ({
    loadedProfiles: this.computedLoadedProfiles()
  }),

   computed: {

    
    computedLoadedProfiles() {
      if (this.$store.state.numberOfProfilesLoaded == this.$store.state.numberOfProfilesLoadedInitially) {
        return this.$store.state.currentProfileList.slice(0, this.$store.state.numberOfProfilesLoadedInitially);
      }
    },

    methods: {
        loadMoreProfiles() {
            if($store.state.scrolledToBottom) {
                loadedProfiles.push(...) //push more profiles to loadedProfiles
            }
        }
    }
    
  },

}
</script>

<style>

</style>

【问题讨论】:

    标签: javascript vue.js vuejs3 vuex


    【解决方案1】:

    在 Vue 中,您可以使用 $set 方法将项目添加到计算属性中的数组。以下是如何在代码中实现此功能的示例:

    <template>
      <div v-for="profile in loadedProfiles" :key="profile.id">
        {{ profile.name }}
      </div>
    </template>
    
    <script>
    export default {
      computed: {
        computedLoadedProfiles() {
          if (this.$store.state.numberOfProfilesLoaded == this.$store.state.numberOfProfilesLoadedInitially) {
            return this.$store.state.currentProfileList.slice(0, this.$store.state.numberOfProfilesLoadedInitially);
          }
        }
      },
      methods: {
        loadMoreProfiles() {
          if (this.$store.state.scrolledToBottom) {
            // Use the $set method to add an item to the array
            this.$set(this.computedLoadedProfiles, this.computedLoadedProfiles.length, ...);
          }
        }
      }
    }
    </script>
    

    请注意,您需要确保 computedLoadedProfiles 数组是反应式的,以便 Vue 知道在您向数组添加项目时更新视图。在上面的示例中,computedLoadedProfiles 数组是响应式的,因为它是由 computedLoadedProfiles 计算属性返回的,该属性在 Vue 中是自动响应式的。

    【讨论】:

      猜你喜欢
      • 2020-12-01
      • 2017-12-10
      • 2018-06-25
      • 2020-02-03
      • 2017-06-01
      • 1970-01-01
      • 2018-02-12
      • 1970-01-01
      • 2016-03-24
      相关资源
      最近更新 更多