搜索框组件是个基础组件,其结构如下:
<template> <div class="search"> <div class="search-box-wrapper"></div> </div> </template> <script> export default { name: 'search', }; </script> <style lang="scss" scoped> .search { .search-box-wrapper { margin: 20px; } .shortcut-wrapper { position: fixed; top: 178px; bottom: 0; width: 100%; .shortcut { height: 100%; overflow: hidden; .hot-key { margin: 0 20px 20px 20px; .title { margin-bottom: 20px; font-size: $font-size-medium; color: $color-text-l; } .item { display: inline-block; padding: 5px 10px; margin: 0 20px 10px 0; border-radius: 6px; background: $color-highlight-background; font-size: $font-size-medium; color: $color-text-d; } } .search-history { position: relative; margin: 0 20px; .title { display: flex; align-items: center; height: 40px; font-size: $font-size-medium; color: $color-text-l; .text { flex: 1; } .clear { @include extend-click(); .icon-clear { font-size: $font-size-medium; color: $color-text-d; } } } } } } .search-result { position: fixed; width: 100%; top: 178px; bottom: 0; } } </style>search-box.vue
在search组件中引入它
<template> <div class="search"> <div class="search-box-wrapper"> <search-box></search-box> </div> </div> </template> <script> import SearchBox from '../../base/search-box/search-box.vue'; export default { name: 'search', components: { SearchBox, }, }; </script>
在搜索框中设置默认文字
<div class="search-box"> <i class="iconfont icon-search"></i> <input class="box" :placeholder="placeholder"/> <i class="iconfont icon-dismiss"></i> </div> export default { props: { placeholder: { type: String, default: '搜索歌曲、歌手', }, }, };
用v-model让input和数据绑定起来,当有数据输入到input时,v-model这个指令对应到query有变化,query有变化对应到v-show就会使icon-dismiss显示。
<div class="search-box"> <i class="iconfont icon-search"></i> <input class="box" v-model="query" :placeholder="placeholder"/> <i v-show="query" class="iconfont icon-dismiss"></i> </div> data() { return { query: '', }; },
添加点击事件:当点击icon-dismiss这个图标时,清空input的内容,并隐藏该图标。
<i @click="clear" v-show="query" class="iconfont icon-dismiss"></i> methods: { clear() { this.query = ''; }, },
这个搜索框的作用就是获取query内容并传递到外面。当query发生改变的时候,组件就会派发事件告诉外部组件'我有变化'
思路:只需要watch这个query,然后把它当作事件的参数派发出去。(这里采用回调的方式)
created() { this.$watch('query', (newQuery) => { this.$emit('query', newQuery); }); },
优化:
点击input时会发现点击不灵敏,没有反应
需要使用fastclick解决这个问题
在main.js中添加以下代码:
fastclick.prototype.focus = function (targetElement) { let length; if (targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') { length = targetElement.value.length; targetElement.focus(); targetElement.setSelectionRange(length, length); } else { targetElement.focus(); } };