1.在stores文件夹下新建重复请求的js文件category.js,并写入代码;
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getCategoryAPI } from '@/apis/layout';
export const useCategoryStore = defineStore('category', () => {
// 导航列表的数据管理
// store 导航列表数据
const categoryList = ref([])
// action 获取导航列表数据的方法
const getCategory = async () => {
const res = await getCategoryAPI()
categoryList.value = res.result
}
return {
categoryList,
getCategory
}
})
2.在公共父组件中获取action;
// 触发获取导航列表的action
import { useCategoryStore } from '@/stores/category'
import { onMounted } from 'vue'
const categoryStore = useCategoryStore()
onMounted(()=>{
categoryStore.getCategory()
})
3.在页面中使用pinia中的数据;
import { useCategoryStore } from '@/stores/category';
// 使用pinia中的数据
const categoryStore = useCategoryStore()
4.在html中使用数据;