300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > vue 实现百度下拉提示搜索功能

vue 实现百度下拉提示搜索功能

时间:2024-03-12 10:26:18

相关推荐

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('/s?wd='+this.keyword);this.keyword=''}this.$http.jsonp('/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>

View Code

说明:

get方法实现获取下拉数据和搜索功能,输入keyword之后,调用get方法使用jsonp获取提示数据,然后赋值给myData,然后使用v-for遍历提示数据

然后selectDown和selectUp实现上下选中数据,当按下回车键时,实现搜索

本文参考链接:

/html/Vue/0621/23154.html

/q/1010000009471910/a-1020000009474506

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。