Code 可以在如下 git 中获取:
https://github.com/slhuang520/vue
项目结构如下:
search.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue Customer Search</title>
<link rel="stylesheet" href="css/search.css">
<script src="../../../lib/vue.min.js"></script>
</head>
<body>
<div id="app">
<div style="float: left;">
<customer-search btn="search" :items="items"></customer-search>
</div>
<div style="float: left; margin-left: 10px;">
<customer-search btn="find" :items="items"></customer-search>
</div>
</div>
<script src="js/search.js"></script>
</body>
</html>
search.css
section {
border: 1px solid grey;
border-radius: 15px;
width: 292px;
}
section h1 {
display: none;
}
section header {
height: 52px;
line-height: 52px;
}
section input {
background: #eee url("../img/search.png") no-repeat 3px;
background-size: 26px;
height: 30px;
line-height: 30px;
width: 200px;
margin: 10px;
border-radius: 15px;
text-indent: 36px;
font-size: 22px;
border: 1px solid orange;
float: left;
}
section input:focus {
outline: none;
}
section button {
border-radius: 15px;
height: 34px;
width: 50px;
border: none;
margin: 10px;
background-color: orange;
float: left;
cursor: pointer;
}
section button:focus {
outline: none;
}
section button:hover {
background-color: #8c2a1b;
}
section ul {
list-style: none;
margin: 0 0 10px 10px;
padding: 0;
width: 200px;
}
section ul li {
height: 26px;
line-height: 26px;
padding-left: 10px;
}
section ul li:first-child {
line-height: 22px;
}
section ul li:hover {
border: none;
background-color: orange;
border-radius: 15px;
cursor: pointer;
}
search.js
Vue.component("customer-search", {
props: ["btn", "items"], // 给自定义组件,添加属性
data: function () { // 注意这里的 data 不能是一个对象,对象会被所有组件所共享
return {
showList: false, // 默认下拉列表是关闭的
val: ""
}
},
methods: {
// 选中下拉列表时
select: function (obj) {
this.showList = false;
this.val = obj.name;
}
},
template: "<section>\n" +
" <h1>Customer Search</h1>\n" + // 这个无用
" <header>\n" +
" <input type=\"text\"" +
" @focus=\"showList=!showList\"" + //获取焦点时,打开下拉列表
" v-model=\"val\"/>\n" + // 给输入框绑定选中的值
" <button>{{btn}}</button>\n" +
" </header>\n" +
" <ul class=\"list\" v-show=\"showList\">\n" + // 展示列表数据
" <li @click=\"select(obj)\" v-for=\"obj in items\" value=\"obj.id\">{{obj.name}}</li>\n" +
" </ul>\n" +
" </section>"
});
var vue = new Vue({
el: "#app",
data: {
items: [ //动态添加数据
{id: 1, name: "html + css"},
{id: 2, name: "html5 + css3"},
{id: 3, name: "javascript"},
{id: 4, name: "angular"},
{id: 5, name: "react"},
{id: 6, name: "vue"},
{id: 7, name: "jquery"},
{id: 8, name: "nodejs"},
{id: 9, name: "backbone"}
]
}
});
页面运行效果如下: