用vue2.0实现点击选中active其他选项互斥的效果

在正常的js中。我们如果要实现点击选中active然后其他取消的效果,我们可以定义一个类,当点击的时候给给多有的dom取消active的类,给当前元素加上这个类名,说的很啰嗦,直接来看代码说话吧(表示楼主用的是jq):

 <style>
  * {
   margin: 0;
   padding: 0;
  }

  li {
   list-style: none;
   width: 100px;
   margin-top: 10px;
   border: 1px solid red;
  }

  li:active {
   cursor: pointer;
  }

  .active {
   background-color: aqua;
  }
 </style>
 <script src="http://g.ydbcdn.com/jquery/latest/jquery.min.js"></script>
</head>
<body>
<ul>
 <li>this is pne</li>
 <li>this is two</li>
 <li>this is three</li>
</ul>
</body>
<script>
 $(() => {
  $("li").click((e) => {
   $("li").removeClass("active");
   $(e.target).addClass("active");
  })
 })
</script>

效果如下图所示:

但是在vue里面,是不提倡进行dom操作的,如果非进行dom的话,vue2.0里面有一个ref的属性,是可以达到dom的效果的。那么接下来我们不接住dom来进行操作:

由于习惯了webpack和vue-cli脚手架,所以楼主所有vue的代码都是放在webpack的脚手架当中进行,还使用了pug和scss的预处理器,vue的代码如下:

<template lang="pug">
 ul
  li(v-for="(item,index) in classArr", @click="result(index)", :class="resultNum === index?'active':''") this is {{item}}
</template>
<style lang="scss">
 li {
  list-style: none;
  width: 100px;
  margin-top: 10px;
  border: 1px solid red;
  &:hover {
   cursor: pointer;
  }
 }
 .active{
  background-color: aqua;
 }
</style>
<script>
 export default{
  data(){
   return {
    classArr: ["one", "two", "three"],
    num:"",
   }
  },
  methods: {
    result(index){
     this.num = index;
    }
  },
  computed:{
    resultNum(){
     return this.num;
   }
  }
 }
</script>

思路如下:

这段代码使用的是index这个关键字,还使用了computed这个计算属性,当当前的index索引与点击的当前元素的下标相同的时候,便会触发active这个类名。说的很简练,不懂的可以加博主一起探讨

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持来客网。