1、stores下新建自己的js
stores/menu.js
import { ref } from 'vue'
import { defineStore } from 'pinia'
export const usetopMenuStore = defineStore('topMenu', () => {
const menuList = ref([])
function getMenuList() {
//此处为从后台获取的数据
menuList.value = [
{ id: 1, name: '0.1元专区' },
{ id: 2, name: '儿科用药' },
{ id: 3, name: '补益安捭' },
{ id: 4, name: '肠胃消化' },
{ id: 10, name: '元专区' },
{ id: 20, name: '儿科用药' },
{ id: 30, name: '补益安捭' },
{ id: 40, name: '肠胃消化' },
{ id: 21, name: '儿科用药' },
{ id: 31, name: '补益安捭' },
{ id: 41, name: '肠胃消化' }
];
}
return { menuList, getMenuList }
})
2、触发getMenuList方法从后台获取数据
import { onMounted } from "vue";
import { usetopMenuStore } from "@/stores/menu.js";
onMounted(() => {
usetopMenuStore().getMenuList();
});
3、使用menuList中数据
active-class="active" 添加激活状态下样式
<div class="item" v-for="item in menuStore?.menuList" :key="item.id">
<RouterLink active-class="active" :to="`/classify/${item.id}`"> {{ item.name }}</RouterLink>
</div>
<script setup>
import { ref, onMounted } from "vue";
import { usetopMenuStore } from "@/stores/menu.js";
const menuStore = usetopMenuStore();
</script>