vue2遍历数组的时候为数组动态的添加id

分别用操作dom和vue完成导航栏的例子实现遍历数组的时候动态的为数组中的元素添加id属性。

预期效果:将数组中的数据展示在页面中,当点击不同的数据的时候,更新被选中数据的样式。

        

目录

1. 用操作dom的方法实现(不推荐)

2. vue中的v-bind实现


1. 用操作dom的方法实现(不推荐)

<template>
<!-- 一级导航栏 -->
    <ul class="nav nav-pills">
      <li><a>一级:</a></li>
      <li><a href="#" @click="liClick(-1)" id = "active" class="all1">全部</a></li>
      <li v-for="(l, index) in Lists" :key="index" @click="liClick(index)">
        <a href="#" class="sele">
          {
   
   { l.name }}
        </a>
      </li>
    </ul>
</template>

<script>
export default {
    methods: {
        
      liClick(index) {
          this.temp = index;
          document.getElementById("active").removeAttribute("id","active");
          if (index >= 0 && index < this.Lists.length) {
              document.getElementsByClassName("sele")[index].setAttribute("id","active");
              this.seen = true;
              this.SecLis = this.Lists[index].cate; 
          } else {
              document.getElementsByClassName("all1")[0].setAttribute("id","active");
              this.seen = false;
          }
       }

    },
</script>

<style scoped>
    #active{
      background-color: gainsboro;
    }
</style>

2. vue中的v-bind实现

<template>
    <ul class="nav nav-pills">
      <li><a>一级:</a></li>
      <li>
        <a href="#" @click="liClick(-1)" :id="currentIndex1 === -1 ? 'active' : ''" class="all1" >全部</a >
      </li>
      <li v-for="(l, index) in Lists" :key="index" @click="liClick(index)">
        <a href="#" class="sele" :id="currentIndex1 === index ? 'active' : ''">
          {
   
   { l.name }}
        </a>
      </li>
    </ul>
</template>

<script>
export default {
    data() {
        return {
            currentIndex1: -1,
        };
    },

    methods: {
        liClick(index) {
            this.currentIndex1 = index;
            if (index >= 0) {
                this.seen = true;
                this.SecLis = this.Lists[index].cate;
            }
        },
    },
}
</script>

<style scoped>
    #active {
        background-color: gainsboro;
    }
</style>

猜你喜欢

转载自blog.csdn.net/weixin_45995139/article/details/125014827
今日推荐