英文:
Best practice of structuring data in a vue app
问题
我有一个Vue项目中有几个视图。其中一些视图中包含相同的组件,这些组件将显示相同的数据。目前,当这些组件被挂载时,我会获取数据。我是否应该在更高层次获取数据,以便只在数据相同时获取一次,以减少请求?我不确定这样做是否符合最佳实践。谢谢。
英文:
I have several views in my vue project. Some of these have the same component in them which will display the same data. At the moment I am getting the data in the components when they are mounted. Should I be getting the data higher up so it is only fetched once if it is the same to minimise requests? I’m not sure what is best practice for this. Thanks
答案1
得分: 0
我对任何商店/全局状态管理都不感兴趣。
它们对我来说只是单例。在 ESM 中,一个模块 *有点像* 一个单例,所以将数据放在一个模块中,并在任何地方使用它 :)
data.js:
```js
import {reactive} from 'vue'
import api from './api.js'
let loadingPromise;
const data = reactive({
// 输入一些默认值以显示或将其标记为尚未加载
loaded: false
})
export function loadData(){
// 首次需求时开始加载数据
loadingPromise ??= api.get('my-endpoint')
// 这将以响应式方式更新您的组件
.then(responseData => Object.assign(data, responseData, {loaded: true}))
return data; // 即使尚未加载,也只需返回响应式数据
}
Component.vue
<script setup>
import {loadData} from './data.js';
const data = loadData();
</script>
<template>
<div v-if="!data.loaded">尚未加载...</div>
<div v-else>
<!-- 在这里显示您的组件内容 -->
</div>
</template>
<details>
<summary>英文:</summary>
I'm not fond of any store/global state management.
They are just singletons for me. In ESM a module is *kinda* a singleton, so put your data in a module and use it in any place you want :)
data.js:
import {reactive} from 'vue'
import api from './api.js'
let loadingPromise;
const data = reactive({
// enter some default values to display or mark it as not loaded
loaded: false
})
export function loadData(){
// start loading data when first demanded
loadingPromise ??= api.get('my-endpoint')
// this will update your components reactively
.then(responseData => Object.assign(data, responseData, {loaded: true}))
return data; // just return the reactive data even if it's not loaded yet
}
Component.vue
<script setup>
import {loadData} from './data.js'
const data = loadData()
</script>
<template>
<div v-if="!data.loaded">Not loaded yet...</div>
<div v-else>
<!-- display your component content here -->
</div>
</template>
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论