【问题标题】:Vue pageable container scrollbar refreshes after fetching every new pageVue 可分页容器滚动条在获取每个新页面后刷新
【发布时间】:2022-12-03 17:51:38
【问题描述】:

我有一个可分页的 div。使用 jquery 滚动功能,当滚动到达 div 底部附近时,我获取新页面。我在父组件中获取新页面 - 比如 App.vue。滚动条在 PropertyBox.vue 中。每当我获取新页面时,我都会更新 App.vue 中的数据,并将其作为属性发送给 PropertyBox。为了能够看到 PropertyBox 中的更改,我更新了它在 App.vue 中的键(如果没有,即使使用了新数据也不会出现更改)。问题在于,因为密钥已更新并且组件已硬重新加载,所以滚动条每次都会回到顶部。我怎样才能克服这个?我应该使用另一种方法来硬重新加载子组件(PropertyBox)吗?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    为了防止每次更新数据时滚动条重置到 div 的顶部,您可以尝试使用 Vuex 等状态管理库来管理组件之间的共享数据。这将允许您更新集中存储中的数据,并防止子组件硬重新加载和重置滚动位置。

    下面是一个示例,说明如何使用 Vuex 管理应用程序中的数据:

    首先,您需要安装 Vuex 库并创建一个新商店:

    // main.js
    import Vuex from 'vuex';
    Vue.use(Vuex);
    
    const store = new Vuex.Store({
      state: {
        // initial state here
      },
      mutations: {
        // mutations to update the state here
      }
    });
    
    new Vue({
      store,
      render: h => h(App),
    }).$mount('#app');
    

    接下来,您可以将要在组件之间共享的数据移动到存储中。例如,您可以将 properties 数组移动到商店的 state 中:

    const store = new Vuex.Store({
      state: {
        properties: [],
      },
      mutations: {
        // mutations to update the state here
      }
    });
    

    然后,在您的父组件 (App.vue) 中,您可以使用 Vuex 中的 mapState 帮助器将存储中的 properties 数组映射到组件中的计算属性:

    // App.vue
    import { mapState } from 'vuex';
    
    export default {
      computed: {
        ...mapState(['properties']),
      },
      methods: {
        async fetchProperties() {
          // fetch new properties and update the store using a mutation
        },
      },
    };
    

    最后,在您的子组件 (PropertyBox.vue) 中,您还可以使用 mapState 帮助器将存储中的 properties 数组映射到组件中的计算属性:

    // PropertyBox.vue
    import { mapState } from 'vuex';
    
    export default {
      computed: {
        ...mapState(['properties']),
      },
      mounted() {
        this.$nextTick(() => {
          // initialize the scroll event listener here
        });
      },
    };
    

    使用此设置,您可以使用突变更新商店中的 properties 数组,更改将自动反映在父组件和子组件中,而无需重置滚动位置。

    【讨论】:

      猜你喜欢
      • 2018-11-09
      • 2021-06-05
      • 2021-03-08
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 2018-03-18
      • 2021-02-13
      • 1970-01-01
      相关资源
      最近更新 更多