vue.js实现搜索框搜索功能

您所在的位置:网站首页 vue搜索框查询 vue.js实现搜索框搜索功能

vue.js实现搜索框搜索功能

2023-10-23 04:06| 来源: 网络整理| 查看: 265

一、布局(基于html、css、vue.js) 1、搜索框: 在这里插入图片描述 (1)、template部分

(2)、style部分

.search width 100% height 4rem background-color rgb(94, 208, 247) .searchInput width 92% margin-top .5rem margin-left 4% line-height 2rem border #ccc 1px solid text-align center font-size 18px

2、搜索结果内容框部分 在搜索框输入城市拼音或城市名,若匹配成功,则在搜索框下的搜素结果内容框进行城市名展示;若匹配不成功,则对用户进行提示。代码写在搜索框后面。

效果图: 在这里插入图片描述 在这里插入图片描述

在这里插入图片描述

(1)、template部分

{{item.name}} 找不到相应结果

(2)、style部分 此处要注意search-content与serach同级,不然会报错。

.search-content z-index 2 overflow hidden position fixed top 6.6rem left 0 right 0 bottom 0 background-color #eee .search-item line-height 3rem padding-left 1rem color #666 font-size 18px background-color #fff

3、逻辑部分 (1)、script部分

export default { name: 'Search', data () { return { // 搜索框关键词,用v-model与input框进行双向绑定 keyword: '', // 搜索到的相应结果返回列表 List: [], timer:null, // 对以下假数据进行搜索,即搜索源 songs: { //假数据格式需注意 "A": [{ "id": 56, "spell": "aba", "name": "阿坝" }, { "id": 57, "spell": "akesu", "name": "阿克苏" }, { "id": 58, "spell": "alashanmeng", "name": "阿拉善盟" }, { "id": 59, "spell": "aletai", "name": "阿勒泰" }, { "id": 60, "spell": "ali", "name": "阿里" }, { "id": 61, "spell": "ankang", "name": "安康" }, { "id": 62, "spell": "anqing", "name": "安庆" }, { "id": 63, "spell": "anshan", "name": "鞍山" }, { "id": 64, "spell": "anshun", "name": "安顺" }, { "id": 65, "spell": "anyang", "name": "安阳" }, { "id": 338, "spell": "acheng", "name": "阿城" }, { "id": 339, "spell": "anfu", "name": "安福" }, { "id": 340, "spell": "anji", "name": "安吉" }, { "id": 341, "spell": "anning", "name": "安宁" }, { "id": 342, "spell": "anqiu", "name": "安丘" }, { "id": 343, "spell": "anxi", "name": "安溪" }, { "id": 344, "spell": "anyi", "name": "安义" }, { "id": 345, "spell": "anyuan", "name": "安远" }], } } }, computed: { //判断关键词是否存在搜索源中,如不在,则“找不到相应结果”显示 // 即通过v-show与hasData绑定来控制“找不到相应结果”的显现 hasData () { return !this.List.length } }, watch: { //监听keyword变化 keyword () { // 使用clearTimeout和setTimeout集流函数,提高代码运行效率 if (this.timer) { clearTimeout(this.timer) } //当删除搜索框内容至空时,搜索结果内容框消失 if (!this.keyword) { this.List = [] return } this.timer = setTimeout(() => { const result = [] // js逻辑主体部分,将关键词拼音字母或汉字与搜索源的spell和name分别进行对比 // 判断关键词是否存在搜索源中 for (let i in this.songs) { this.songs[i].forEach((value) => { if (value.name.indexOf(this.keyword) > -1 || value.spell.indexOf(this.keyword) > -1) { result.push(value) } }) } this.List = result }, 100) //延时100ms执行 } }, },

注:其中为了代码简便,可以将假数据写在一个json文件中,通过父子组件传值的方式来获取假数据:

在这里插入图片描述 (1)、父组件:

(2)、子组件:

props: { songs: Object, },

推荐:当搜索结果超过搜索结果内容框的高度时,无法进行滚动,多余部分被遮挡,此时可以引用better-scroll组件,详情可参考better-scroll

在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3