Vue仿百度搜索功能
學(xué)習(xí)vue的第二節(jié),由于2.0版本并不向下兼容,視頻中的不少內(nèi)不能實(shí)現(xiàn)。下面列出一些主要知識點(diǎn)
// v-on 可簡寫為@// 事件冒泡是指當(dāng)點(diǎn)擊div內(nèi)部的button觸發(fā)show1()時,必然會冒泡到div上執(zhí)行show2(),這才層級div中很常見// 阻止冒泡,原生js法,設(shè)置事件對象的cancelBubble屬性為true// vue方法@click.stop// 阻止默認(rèn)行為,原生js法,設(shè)置事件對象的preventDefault屬性為true// vue方法@contextmenu.prevent// 鍵盤事件獲取鍵碼,原生js法,使用事件對象的keyCode屬性// vue方法@keyup.鍵碼或鍵名,如獲取按下回車@keydown.13 或 @keydown.enter// 綁定屬性v-bind:src,簡寫 :src 只綁定一次使用v-once,將綁定內(nèi)容轉(zhuǎn)義成html使用v-html基本知識:
vue
$http.jsonp().then():class@keyup@keydown
配置庫文件
<script src='http://www.b3g6.com/bcjs/libvue.js'></script><!-- vue本身不支持?jǐn)?shù)據(jù)交互,必須引入vue-resource.js,現(xiàn)在vue官方也推薦axios.js--><script src='http://www.b3g6.com/bcjs/libvue-resource.js'></script>
Script
<script> window.onload = function() { new Vue({el: ’#box’,data: { myData: [], content: ’’, now: -1,},methods: { get: function(ev) { // 這里的鍵碼只能通過事件對象$event傳進(jìn)來,因?yàn)檩斎氪蠖鄶?shù)鍵都應(yīng)該可以進(jìn)行搜素,我們要排除的就是up(38)和down(40) if (ev.keyCode == 38 || ev.keyCode == 40) { return; } // 這里當(dāng)按下的鍵是Enter時,應(yīng)實(shí)現(xiàn)搜索跳轉(zhuǎn)功能 if(ev.keyCode == 13) { window.open(’https://www.baidu.com/s?wd=’ + this.content); this.content = ’’; } this.$http.jsonp(’https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=’ + this.content, { jsonp: ’cb’ }).then(function(res) { this.myData = res.data.s; }, function() { alert('搜索失敗'); }) }, changeDown: function() { this.now++; if(this.now == this.myData.length) { this.now = -1; } // 這里實(shí)現(xiàn)輸入框中也顯示同樣的內(nèi)容 this.content = this.myData[this.now]; }, changeUp: function() { this.now--; if (this.now == -2) { this.now = this.myData.length; } this.content = this.myData[this.now]; }}, }) }</script>
三個方法:get()用于對百度進(jìn)行數(shù)據(jù)交互;cheangeDown()用于實(shí)現(xiàn)選中區(qū)域下移;changeUp()用于實(shí)現(xiàn)選中區(qū)域上移
HTML
<body> <div id='box'> <input type='text' name='' id='' v-model='content' @keyup='get($event)' @keydown.down='changeDown()' @keydown.up='changeUp()'> <ul> <!-- 這里注意給class添加屬性的時候采用的是{屬性:true/false}的形式 --> <li v-for='(item, index) in myData' :class='{grey: index==now}'>{{item}} </li> </ul> <p v-show='myData.length == 0'>暫無數(shù)據(jù)...</p> </div></body>
效果

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:

網(wǎng)公網(wǎng)安備