vue 下拉框自定義 以及點擊空白空白處關閉下拉框


html:

<div class="divInput" v-close>
    <div class="input" @click="opensort">
      <input v-model="sortvalue" type="text" placeholder="分類" />
      <vicon :type="'triangle'" class="topimg" />
    </div>
    <div class="list" v-show="show">
      <ul>
        <li
          @click="getvalue(index, sortitem)"
          v-for="(sortitem, index) in tableData"
          :key="sortitem.index"
        >
          {{ sortitem.name }}
        </li>
      </ul>
    </div>
  </div>
View Code

js:

<script>
export default {
  name: "docselect",
  data() {
    return {
      tableData: [
        {
          name: "專業論文"
        },
        {
          name: "植物設計"
        },
        {
          name: "景觀設計"
        },
        {
          name: "規划研究"
        },
        {
          name: "生態理念"
        },
        {
          name: "施工技術"
        },
        {
          name: "工程管理"
        }
      ],
      show: false,
      sortvalue: ""
    };
  },
  methods: {
    opensort() {
      this.show = !this.show;
    },
    getvalue(index, sortitem) {
      this.sortvalue = sortitem.name;
      this.show = false;
    }
  },
  components: {
    vicon
  }
};
</script>
View Code

 css:

<style>
.divInput {
  width: 78px;
  height: auto;
  /* margin-left: 48px; */
  display: inline-block;
}
ul li {
  list-style: none;
}
.input {
  width: 74px;
  height: 20px;
  line-height: 40px;
  padding-left: 5px;
  /* border: 1px solid #cccccc; */
  position: relative;
  cursor: pointer;
}
.input input:focus {
  outline: 0 !important;
}
.input input {
  border: none;
  outline: none;
  width: 55px;
  float: left;
  margin: auto;
  cursor: pointer;
  margin-top: 2px;
}

.input img {
  position: absolute;
  right: 34px;
  top: 48%;
}
.list {
  background: #ffffff;
  width: 72px;
  overflow: hidden;
  position: absolute;
  box-shadow: 0px 3px 6px rgba(191, 191, 191, 1);
  opacity: 1;
  z-index: 1;
  display: block;
}
.list.close {
  display: none;
}
.topimg {
  width: 18px;
  height: 15px;
  float: left;
}
.list ul li {
  height: 30px;
  cursor: pointer;
  margin: 0px 4px 0px -35px;
  font-size: 12px;
}
.list ul li:hover {
  background-color: #e6e6e6;
}
</style>
View Code

 

然后發現下拉框點擊空白處不關閉,然后在加上一個事件

  //點擊空白處關閉下拉框的div事件
  directives: {
    close: {
      inserted(el, binding, vnode) {
        window.onclick = function(e) {
          if (!el.contains(e.target)) {
            vnode.context.show = false;
          }
        };
      }
    }
  },


注意:這個事件和data是同級的

 

效果圖:

           

最后發現如果兩個下拉框就只能觸發一個下拉框點擊空白處關閉,之后在給事件修改一下,

directives: {
    close: {
      inserted(el, binding, vnode) {
        window.addEventListener("click", e => {
          if (!el.contains(e.target)) {
            vnode.context.show = false;
          }
        });
      }
    }
  },



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM