温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-06-26 13:55:08 来源:亿速云 阅读:177 作者:小新 栏目:web开发

这篇文章主要介绍了如何使用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>

效果如下图所示:

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

但是在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>

感谢你能够认真阅读完这篇文章,希望小编分享的“如何使用vue2.0实现点击选中active其他选项互斥的效果”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI