
优化vuex后端全局数据加载
后端提供全局共享数据接口时,为提升应用性能,最佳实践是在实际需要数据时再发起请求获取。 避免使用简单的判断和dispatch方式,因为它会产生冗余代码。
高效解决方案
推荐如下简洁方案:
<code class="javascript">// store:
export default {
namespaced: true,
state: {
platformList: []
},
mutations: {
setPlatformList(state, list) {
state.platformList = list;
}
},
actions: {
async getPlatformList({ commit, state }) {
if (state.platformList.length) {
// 数据已存在,直接返回
return state.platformList;
}
try {
const { data } = await api.get('platform/list');
commit('setPlatformList', data);
return data;
} catch (error) {
throw error; // 将错误抛出,以便组件处理
}
}
}
};</code>在组件中调用:
立即学习“前端免费学习笔记(深入)”;
<code class="javascript">// vue:
async mounted() {
try {
this.platformList = await this.$store.dispatch('platform/getPlatformList');
} catch (error) {
// 处理错误
console.error("Failed to fetch platform list:", error);
}
}</code>此方法确保在使用前获取数据,同时避免了不必要的代码重复,并使用async/await简化了异步操作的处理,并添加了错误处理机制。
以上就是Vuex如何优雅地按需加载后端全局数据?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号