若两个组件请求的数据是相同的,避免请求两次,可以使用Pinia集中管理数据,再由父组件请求,子组件使用
1.
// category.js
import {defineStore} from "pinia";
import {ref} from "vue";
import {getCategoryAPI} from "@/apis/layout";
export const useCategoryStore = defineStore('category',()=>{
// 导航列表逻辑
// state
const categoryList = ref([])
// action
const getCategory = async ()=>{
const res = await getCategoryAPI()
console.log(res)
categoryList.value=res.result
}
return {categoryList,getCategory}
})
2.文章来源:https://www.toymoban.com/news/detail-521352.html
// 父组件
<template>
<div>
<!--二级路由-->
<LayoutFixed></LayoutFixed>
<LayoutHeader></LayoutHeader>
<router-view></router-view>
</div>
</template>
<script setup>
import LayoutHeader from "@/views/Layout/components/LayoutHeader.vue";
import LayoutFixed from "@/views/Layout/components/LayoutFixed.vue";
// 触发获取导航列表的action
import {useCategoryStore} from "@/stores/category";
import {onMounted} from "vue";
const categoryStore = useCategoryStore()
onMounted(()=>categoryStore.getCategory())
3.文章来源地址https://www.toymoban.com/news/detail-521352.html
// 子组件1
<script setup>
import {useCategoryStore} from "@/stores/category";
const categoryStore=useCategoryStore()
</script>
<template>
<ul class="app-header-nav">
<li class="home" v-for="item in categoryStore.categoryList" :key="item.id">
<RouterLink to="/">{{ item.name }}</RouterLink>
</li>
</ul>
</template>
到了这里,关于Vue3---Pinia优化重复请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!