今天完成的是自定義下拉框,涉及組件,組件註冊、組件間通信,關於組件間通信,老師有張ppt感覺挺好,如下圖:
完成效果圖如下:
LICEcap截圖
頁面代碼:
<html>
<head>
<title>vue練習之select</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="./select.css" />
<script type="text/javascript" src="../vue.js"></script>
</head>
<body>
<div id="app">
<div class="left">
<h2>自定義下拉框</h2>
<custom-select btn-value="查詢" v-bind:list="list1"></custom-select>
</div>
<div class="left">
<h2>自定義下拉框2</h2>
<custom-select btn-value="搜索" v-bind:list="list2"></custom-select>
</div>
</div>
<script type="text/javascript">
//註冊組件 全局
Vue.component("custom-select",{
data:function(){
return {
selectShow:false,
val:"",
}
},
props:["btnValue","list"],
template:`<section class="warp">
<div class="searchIpt clearFix">
<div class="clearFix">
<input type="text" class="keyWord" @click="selectShow=!selectShow" :value="val" />
<input type="button" class="search" :value="btnValue" />
<span></span>
</div>
<custom-list
v-show="selectShow"
:list="list"
@receive="changeValueHandle"
></custom-list>
</div>
</section>`,
methods:{
changeValueHandle(value){
this.val = value;
}
}
})
Vue.component("custom-list",{
props:["list"],
template:`<ul class="list">
<li v-for="item of list" @click="selectVuleHandle(item)">{{item}}</li>
</ul>`,
methods:{
selectVuleHandle:function(item){
//告知父級,改變val的值,需要觸發自定義事件
this.$emit("receive",item);
},
}
})
var data = {
list1:["北京","天津","河北"],
list2:["11","22","33","44"]
}
new Vue({
el:"#app",
data:data,
})
</script>
</body>
</html>
源碼地址:GitHub