vue 实现百度下拉提示搜索功能
一、概述
使用百度实现搜索功能,先来看一下效果图
二、代码实现
安装插件vue-resource
npm install vue-resource --save
这个插件主要是为了实现this.$http.jsonp()方法
修改main.js,引用vue-resource
import VueResource from 'vue-resource'
Vue.use(VueResource)
test.vue

<template> <div class="container search-container"> <h1 class="title">baidu-search</h1> <input type="text" class="form-control" placeholder="请输入想要搜索关键字" v-model="keyword" @keyup="get($event)" @keydown.down.prevent="selectDown" @keydown.up.prevent="selectUp"> <ul> <li class="text-left" v-for="(value,index) in myData"><span class="text-success textprimary" :class="{gray:index==now}">{{value}}</span></li> </ul> <p> <h2 v-show="myData.length==0" class="text-warning text-left">(*^__^*)暂时没有数据</h2> </p> </div> </template> <script> export default { data() { return { myData:[], keyword:'', now:-1 } }, methods:{ get:function (event) { if(event.keyCode==38||event.keyCode==40)return; if(event.keyCode==13){ window.open('https://www.baidu.com/s?wd='+this.keyword); this.keyword='' } this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?', { params: { wd: this.keyword }, jsonp: 'cb' }).then((res) => { console.log("res11",res) this.myData = res.body.s }) }, selectDown:function () { this.now++; if(this.now==this.myData.length)this.now=-1; console.log(this.now) this.keyword=this.myData[this.now]; }, selectUp:function () { this.now--; if(this.now==-2)this.now=this.myData.length-1; this.keyword=this.myData[this.now]; } } } </script> <style scoped> /*body {*/ /* background-image: url("../../assets/background.jpg");*/ /* background-size: cover;*/ /*}*/ .title { color: #ffffff; text-align: left; } .gray { background-color: #dff0d8; } .textprimary { color: #3c763d; text-align: left; font-family: "Microsoft YaHei UI"; font-size: larger; font-weight: bolder; font-size: 16px; } ul { list-style: none; top: 0px; left: -40px; right: 0px; position:relative; } ul :hover { cursor: pointer; background-color:#EEEEEE } li { list-style: none; top: 0px; left: 0px; right: 0px; } </style>
说明:
get方法实现获取下拉数据和搜索功能,输入keyword之后,调用get方法使用jsonp获取提示数据,然后赋值给myData,然后使用v-for遍历提示数据
然后selectDown和selectUp实现上下选中数据,当按下回车键时,实现搜索
本文参考链接:
http://www.uxys.com/html/Vue/20170621/23154.html
https://segmentfault.com/q/1010000009471910/a-1020000009474506
分类:
python 运维开发
标签:
vue
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
2018-03-26 python 全栈开发,Day7(元组转换,列表以及字典的坑,集合,关系测试,深浅copy,编码补充)