1.项目展示
以一个非常非常常用的功能为例,收缩侧边菜单栏
结构介绍
很明显 是 header 里面的组件 控制 menu里面的组件,所以需要用到VUEX配置全局状态
2.全局状态配置
store/index.ts
import { InjectionKey } from "vue";
import { createStore, useStore as baseUseStore, Store } from "vuex";
import { ITabe } from "./type";
export interface State {
// 1。定义一个 菜单栏收缩的 全局状态 collapse true是关闭 false是打开
collapse: boolean;
}
export const key: InjectionKey<Store<State>> = Symbol();
export const store = createStore<State>({
state: {
// 2。collapse 默认 状态设置
collapse: false,
},
mutations: {
// 3。设置展开和收缩菜单栏
setCollapse(state: State, collapse: boolean) {
state.collapse = collapse;
},
},
getters: {
// 4.获取 菜单栏收缩
getCollapse(state: State) {
return state.collapse;
},
},
});
// 定义自己的 `useStore` 组合式函数
export function useStore() {
return baseUseStore(key);
}
main.ts 引入
import { store, key } from "./store/index";
const app = createApp(App)
app.use(store, key);
app.mount("#app");
3.页面接受
menu/MenuBar
<template>
<MenuLogo v-if="!isCollapse"></MenuLogo>
<el-menu
:default-active="activeIndex"
class="el-menu-vertical-demo"
:collapse="isCollapse"
background-color="#304156"
@open="handleOpen"
@close="handleClose"
router
>
<MenuItem :menuList="menuList"></MenuItem>
</el-menu>
</template>
// 菜单栏收缩状态
import { useStore } from "@/store/index";
// 上面这里一定不要引入 vuex ,引入自己定义的 useStore 不然报错 : getters 找不到
const store = useStore();
const isCollapse = computed(() => {
return store.getters["getCollapse"];
});
header/Collapse
<template>
<el-icon class="icons" @click="changeIcon">
<component :is="status ? 'expand' : 'fold'" /> // 这里用法 elUI 文档有说明
</el-icon>
</template>
<script lang="ts" setup>
import { computed } from "vue";
import { useStore } from "@/store/index";
const store = useStore();
const status = computed(() => {
return store.getters["getCollapse"];
});
const changeIcon = () => {
store.commit("setCollapse", !status.value);
};
</script>