发布时间:2021-04-02 13:25:49编辑:admin阅读(3187)
使用百度实现搜索功能,先来看一下效果图
安装插件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
上一篇: vue 中父级样式深度覆盖子组件
47605
45985
36909
34469
29080
25713
24566
19714
19245
17756
5565°
6155°
5691°
5737°
6705°
5483°
5484°
5988°
5965°
7295°