【小技巧】js简写

4 篇文章 0 订阅
3 篇文章 0 订阅
本文通过一个Vue.js实现的手风琴效果展示了如何优雅地控制元素的显隐,使用一个状态变量记录而不直接修改原数组。同时,文章介绍了使用`includes`代替多个条件判断以及用对象键值对替换`switch`语句的优化技巧,提升代码可读性和效率。
摘要由CSDN通过智能技术生成

1.控制显隐:单独用一个变量记录状态,不去改变原数组
手风琴效果:

<template>
  <div class="home">
    <ul>
      <li v-for="(item, index) in list" :key="index" @click="changeOne(item)">
        <div>
          <span>{{ expandList.indexOf(item.id) > -1 ? "-" : "+" }}</span>
          <span>{{ item.title }}</span>
        </div>
        <div class="content" v-if="expandList.indexOf(item.id) > -1">
          {{ item.content }}
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: "Home",
  components: {},
  data() {
    return {
      expandList: [],
      list: [
        { id: 1, content: "这是内容1", title: "这是标题1" },
        { id: 2, content: "这是内容2", title: "这是标题2" },
        { id: 3, content: "这是内容3", title: "这是标题3" },
        { id: 4, content: "这是内容4", title: "这是标题4" },
      ],
    };
  },
  methods: {
    change(item) {
      // 点击就展开 收起
      const index = this.expandList.findIndex((e) => e === item.id);
      // expandList数组中包含就删除 不包含就删除 根据数组中是否有值来控制展开收起
      index > -1
        ? this.expandList.splice(index, 1)
        : this.expandList.push(item.id);
    },
    changeOne(item) {
      // 每次只能点击一个展开
      const index = this.expandList.findIndex((e) => e === item.id);
      this.expandList = []; // 每次切换先将数组清空,点击的不是自身则添加 --每次最多展开一个
      if (index === -1) {
        this.expandList.push(item.id);
      }
    },
  },
};
</script>

<style scoped lang="less">
li {
  span {
    cursor: pointer;
  }
  .content {
    margin-left: 20px;
  }
}
</style>

2,用include代替一个一个的判断

  hasAnimals(type) {
      const animals = ["cat", "pig", "dog"];
      // return type === "cat" || type === "pig" || type === "dog";
      return animals.includes(type);
    },

3,用键值对obj[key]代替switch

  findType(type) {
      const mime = {
        ".323": "text/h323",
        ".3gp": "video/3gpp",
        ".aab": "application/x-authoware-bin",
        ".aam": "application/x-authoware-map",
        ".aas": "application/x-authoware-seg",
      };
      return mime[type];
      // switch (type) {
      //   case ".323":
      //     return "text/h323";
      //     break;
      //   case ".3gp":
      //     return "video/3gpp";
      //     break;
      //   case ".aab":
      //     return "application/x-authoware-bin";
      //     break;
      // }
    },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值