如果你是一个前端开发工程师,你需要在vue项目中实现一个瓜子二手车app首页顶部的搜索框,请写出代码
时间: 2024-02-22 15:01:24 浏览: 20
好的,以下是一个简单的例子代码:
在父组件中,我们可以使用以下方式调用搜索框组件:
```html
<template>
<div>
<SearchBox @search="handleSearch" />
</div>
</template>
<script>
import SearchBox from '@/components/SearchBox.vue';
export default {
components: {
SearchBox,
},
methods: {
handleSearch(keyword) {
// 处理搜索请求
},
},
};
</script>
```
在搜索框组件(SearchBox.vue)中,我们可以使用以下代码实现:
```html
<template>
<div class="search-box">
<input type="text" v-model="keyword" placeholder="请输入关键词" />
<button @click="handleSearch">搜索</button>
</div>
</template>
<script>
export default {
data() {
return {
keyword: '',
};
},
methods: {
handleSearch() {
this.$emit('search', this.keyword);
},
},
};
</script>
<style scoped>
.search-box {
display: flex;
justify-content: center;
align-items: center;
height: 50px;
}
.search-box input {
flex: 1;
height: 100%;
padding: 0 10px;
border: none;
outline: none;
font-size: 16px;
}
.search-box button {
width: 80px;
height: 100%;
border: none;
outline: none;
background-color: #ff9700;
color: #fff;
font-size: 16px;
cursor: pointer;
}
</style>
```
在上面的代码中,我们创建了一个名为`SearchBox`的组件,并在组件中添加了一个输入框和一个按钮。输入框的值通过`v-model`指令绑定到组件内部的`keyword`属性上,按钮的点击事件会触发`handleSearch`方法,该方法会通过`$emit`方法向父组件发送一个名为`search`的事件,并传递当前输入框中的关键词作为参数。在父组件中,我们通过`@search`监听该事件,并在`handleSearch`方法中处理搜索请求。