美文网首页
vue 自定义组件 横向菜单-简单版本

vue 自定义组件 横向菜单-简单版本

作者: 微笑中的你 | 来源:发表于2021-01-18 11:02 被阅读0次

无图无真相!!!


lz-menu1.gif

缺点: 无法自动滚动,无法外部传递参数控制颜色等

请参考升级版 点击选项自动居中

开发环境

vue 2.x
scss

组件 LzMenu.vue

<template>
  <div class="wrapper">
    <div class="my-inbox" ref="box">
      <span
        class="item"
        v-for="(item, index) in menuItems" :key="index"
        v-bind:class="{active: index == currentIndex}"
        @click="clickMenuItem(index)"
        >{{ item.name }}</span>
    </div>
  </div>
</template>

<script>
export default {
  name: "lz-menu",
  props: {
    menuItems: Array,
    selectedIndex: 0,
  },
  data() {
    return {
      normalColor: "#fff",
      activeColor: "#f00",
      currentIndex: 0,
    };
  },
  onMounted() {
    currentIndex = selectedIndex;
  },
  methods: {
    getStyle(normal) {
      return {
        color: normal ? this.normalColor : this.activeColor,
      };
    },
    clickMenuItem(idx) {
      if (this.currentIndex != idx) {
        let inbox = this.$refs.box;
        this.currentIndex = idx;
        console.log("点击index: " + idx);
        this.$emit('clickLzMenuItem', this.menuItems[idx]);

      }
    },
  },
};
</script>

<style lang="scss" scoped>
.wrapper {
  background-color: #f2f2f2;
  width: 100%;
  .my-inbox {
    overflow-y: hidden;
    overflow-x: scroll;
    width: 100%;
    white-space: nowrap;
    .item {
      display: inline-block;
      height: 2rem;
      line-height: 2rem;
      margin: 0.5rem;
      padding: 0px 0.8rem;
      text-align: center;
    }
    .active {
      background-color: rgb(7, 177, 35);
      font-weight: bold;
      border-radius: 25px;
      color: #fff;
    }
  }
}
</style>

使用

<template>
  <div>
    <lz-menu :menuItems="menuItems" @clickLzMenuItem="clickMenuItem" />
  </div>
</template>

<script>
import LzMenu from "../components/LzMenu.vue";
export default {
  components: {
    LzMenu,
  },
  name: "Setting",
  data() {
    return {
      menuItems: [
        {
          id: 1,
          name: "第 1 个",
        },
        {
          id: 2,
          name: "第 2 个",
        },
        {
          id: 3,
          name: "第 3 个",
        },
        {
          id: 4,
          name: "第 4 个",
        },
        {
          id: 5,
          name: "第 5 个",
        },
        {
          id: 6,
          name: "第 6 个",
        },
        {
          id: 7,
          name: "第 7 个",
        },
        {
          id: 8,
          name: "第 8 个",
        },
      ],
    };
  },
  methods: {
    clickMenuItem: function(item) {
      console.log(item.name);
    }
  },
};
</script>

<style>
</style>

相关文章

网友评论

      本文标题:vue 自定义组件 横向菜单-简单版本

      本文链接:https://www.haomeiwen.com/subject/gcwtzktx.html