vue封装一个搜索组件
话不多说,直接上代码!!!
搜索组件:
<!-- -->
<template>
<div>
<input
type="text"
v-model="inputValue"
placeholder="请输入"
@input="getValue"
@keydown.enter="search"
/>
</div>
</template>
<script>
export default {
name: "app",
components: {},
data: function() {
return {
inputValue: "" //默认搜索框的值是空
};
},
methods: {
getValue(e) {
// 拿到输入框的值
console.log(e.target.value);
this.inputValue = e.target.value;
// console.log(this.inputValue);
},
search(){
if(this.inputValue==""){
alert('不能为空')
}else{
this.inputValue!==""
this.$emit('sou',this.inputValue);
alert('发送成功')
}
}
}
};
</script>
<style scoped>
/* @import url(); 引入css类 */
</style>
父组件引用:
<template>
<div class="home">
<search @sou="go" />
<div class="box">
<div v-for="(item,index) in this.arr" :key="index">{{item}}</div>
</div>
</div>
</template>
<script>
// @ is an alias to /src
import search from "../components/search";
export default {
name: "Home",
components: {
search
},
data: function() {
return {
list: [1, 2, 3, 4, 5],
arr: []
};
},
methods: {
go(e) {
var temp = [];
window.console.log(e, "父组件");
this.list.forEach(el => {
if (el == e) {
temp.push(e);
this.arr = temp;
}
});
}
}
};
</script>
<style scoped>
.box {
width: 200px;
height: 200px;
border: 1px solid red;
}
</style>