以下是一个简单的左侧菜单栏组件示例,使用Vue3的Composition API:

<template>
  <div class="sidebar">
    <div v-for="(item, index) in menuItems" :key="index" class="menu-item" :class="{ active: item.active }" @click="selectMenuItem(item)">
      <i :class="item.icon"></i>
      <span>{{ item.label }}</span>
    </div>
  </div>
</template>

<script>
import { reactive } from "vue";

export default {
  setup() {
    const menuItems = reactive([
      {
        label: "Dashboard",
        icon: "fa fa-tachometer-alt",
        active: true
      },
      {
        label: "Users",
        icon: "fa fa-users",
        active: false
      },
      {
        label: "Settings",
        icon: "fa fa-cog",
        active: false
      }
    ]);

    const selectMenuItem = (item) => {
      menuItems.forEach((i) => (i.active = false));
      item.active = true;
      // TODO: Emit event to parent component to update content based on selected menu item
    };

    return {
      menuItems,
      selectMenuItem
    };
  }
};
</script>

<style>
.sidebar {
  width: 200px;
  height: 100%;
  background-color: #333;
  color: #fff;
  padding: 20px;
  box-sizing: border-box;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}

.menu-item.active {
  background-color: #555;
}

.menu-item i {
  margin-right: 10px;
}
</style>

在上述代码中,我们定义了一个menuItems数组来存储菜单项的信息。使用reactive函数将其转化为响应式对象,以便在后续更改菜单项时能够自动更新视图。

组件中的selectMenuItem方法用于选择菜单项并更新其活动状态。它会将所有菜单项的active属性设置为false,然后将选定的菜单项的active属性设置为true。您可以在此方法中添加自己的逻辑,例如发出事件以通知父组件选中的菜单项或更新内容区域等。

最后,我们在模板中使用v-for循环遍历菜单项,并根据其活动状态为其添加active类。当单击菜单项时,将调用selectMenuItem方法并更新菜单项的状态。此外,我们还使用class绑定指令根据菜单项的active属性为其添加active类。最后,我们使用i元素和FontAwesome字体图标类为菜单项添加图标。

用vue3写一个后台管理系统左侧菜单栏

原文地址: https://www.cveoy.top/t/topic/bq1Z 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录