vue-cli中实现下拉框点击其他区域消失
<div class="sn-search-nav">
  <a :class="['head-item',{active:first}]" @click="oFirst">排序</a>
  <ul class="nav-down" v-if="first">
   <li v-for="sort in sorts.defaults" @click="selected(sort)" :class="{active: activeName == sort}">{{sort}}<a v-if="activeName == sort">选中显示</a></li>
  </ul>
</div>

<script>
export default {
  name: 'hello',
  data () {
    return {
           show: false
      activeName:'',
      sorts :{
        "defaults":['销量排序','价格从高到低','价格从低到高','评分排序','最新上架']
      }
    }
  },
  methods:{
    oFirst(){
      this.show=true;
    }
selected(name) {
    this.activeName = name
  }
},
mounted() { document.addEventListener('click', (e) => { if (!this.$el.contains(e.target)) this.show = false }) }
}
</script>
点击li时selected函数改变activeName值,li标签中分配的字符与activeName匹配则增加active class名。
点击其他区域的时候利用this.$el.contains(e.target)判断点击区域是否是当前模块
Logo

前往低代码交流专区

更多推荐