为了防止每次更新数据时滚动条重置到 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 数组,更改将自动反映在父组件和子组件中,而无需重置滚动位置。