首頁  >  文章  >  web前端  >  如何寫出vue.js選單元件

如何寫出vue.js選單元件

coldplay.xixi
coldplay.xixi原創
2020-11-24 16:12:413084瀏覽

寫出vue.js選單元件的方法:先使用【index.html】寫入口頁面;然後使用【clickoutside.js】下拉框元件,程式碼為【Vue.directive('clickoutside'】;最後實作樣式表。

如何寫出vue.js選單元件

【相關文章推薦:vue.js
本教學操作環境:windows7系統、Vue2 .9.6版,此方法適用於所有品牌電腦。

寫出vue.js選單元件的方法:

1、入口頁index.html

<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 <title>可从外部关闭的下拉菜单</title>
 <link rel="stylesheet" type="text/css" href="style.css" >
</head>
<body>
 <div id="app" v-cloak>
  <div v-clickoutside="handleClose">
   <button @click="show = !show">点击显示下拉菜单</button>
   <div v-show="show">
    <p>下拉框的内容,点击外面区域可以关闭</p>
   </div>
  </div>
 </div>
 <script src="https://unpkg.com/vue/dist/vue.js"></script>
 <script src="clickoutside.js"></script>
 <script src="index.js"></script>
</body>
</html>

2、根實例index.js

var app = new Vue({
 el: &#39;#app&#39;,
 data: {
  show: false
 },
 methods: {
  handleClose () {
   this.show = false;
  }
 }
});

3、下拉方塊元件clickoutside.js

Vue.directive(&#39;clickoutside&#39;,{
 bind: function (el, binding, vnode) {
  function documentHandler(e) {
   if(el.contains(e.target)){
    return false;
   }
   if(binding.expression){
    binding.value(e);
   }
  }
  el.__vueClickOutside__ = documentHandler;
  document.addEventListener(&#39;click&#39;,documentHandler);
 },
 unbind: function (el, binding) {
  document.removeEventListener(&#39;click&#39;, el.__vueClickOutside__);
  delete el.__vueClickOutside__;
 }
});

4、樣式表

[v-cloak]{
 display: none;
}
.main{
 width: 125px;
}
button{
 display: block;
 width: 100%;
 color: #fff;
 background-color: #39f;
 border: 0;
 padding: 6px;
 text-align: center;
 font-size: 12px;
 border-radius: 4px;
 cursor: pointer;
 outline: none;
 position: relative;
}
button:active{
 top:1px;
 left: 1px;
}
.dropdown{
 width:100%;
 height: 150px;
 margin: 5px 0;
 font-size: 12px;
 background-color: #fff;
 border-radius: 4px;
 box-shadow: 0 1px 6px rgba(0,0,0,.2);
}
.dropdown p{
 display: inline-block;
 padding: 6px;
}

相關免費學習推薦:JavaScript(影片)

以上是如何寫出vue.js選單元件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn