1. 程式人生 > 實用技巧 >vue中的百度搜索案列

vue中的百度搜索案列

百度搜索的案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./node_modules/vue/dist/vue.js"></script>
<style>
.select {
background: #ccc;
}
</style>
</head>
<!--
百度搜索資料思路:
一、我們要監聽到使用者實時輸入的資料同時我們要實時調取介面
二、把調取介面之後的返回值渲染到頁面中
調取介面面臨著跨域問題:調取ajax的時候
解決跨域問題的方法???
①誰去解決跨域問題?
首先要分環境,在生產環境下出現跨域問題,前端無法解決,必須由後端去解決,在Nignx上解決(Nginx (engine x) 是一個高效能的HTTP和反向代理web伺服器)
②在開發環境下,出現跨域問題,前端解決
jsonp可以解決跨域問題,但是在真正的專案很少用
webpack可以解決跨域,這個方法是我們在做專案框架的過程中經常的用的方法,只做程式碼配置
三、當前百度案例調取介面,我們選擇沒有跨域問題的方式
jsonp
四、jsonp的原理是什麼? src href這些屬性沒有跨域問題
①建立一個script標籤
let script = document.createElement('script')
② 建立src屬性
script.src = 'url地址'
③把建立好的標籤插入body中
document.body.appendChild(script)
-->

<body>
<div id="app">
<div>
請輸入搜尋內容:
<input
type="text"
v-model="val"
@keydown.down="down"
@keydown.up="up"
@keydown.enter="enter"
/>
</div>
<!-- 迴圈遍歷搜尋結果 -->
<ul>
<!-- i <4 0 1 2 3 -->
<li :class="[i==num?'select':'']" v-for="(item,i) in arr" v-if="i<4">
{{item}}
</li>
</ul>
</div>
<script>
let vm = new Vue({
el: "#app",
data: {
msg: "今天是週一",
val: "",
arr: [],
num: -1,
},
methods: {
//鍵盤下箭頭事件
down() {
console.log(this.num, "初始");
if (this.num >= 4) {
this.num = 0;
return;
}
this.num++;
console.log(this.num, "更新");
},
//鍵盤上箭頭事件
up() {
if (this.num < 0) {
this.num = 3;
return;
}
this.num--;
},
//回車事件,當用enter的時候跳轉到搜尋結果
enter() {
//跳轉連結
//搜尋列表:http://www.baidu.com/s?wd=
// window.open() 在新頁面開啟連結
// window.open('http://www.baidu.com/s?wd='+this.arr[this.num])
//window.location.href屬性在當前頁面開啟連結
window.location.href =
"http://www.baidu.com/s?wd=" + this.arr[this.num];
},
},
watch: {
//axios 它是基於node.js開發的http庫
val(newVal, oldVal) {
//剔除空值
if (newVal == "") {
this.arr = [];
return;
}
console.log(newVal, "新值");
//呼叫jsonp介面
//建立script標籤
let script = document.createElement("script");
//新增src屬性
script.src = "http://suggestion.baidu.com/su?cb=aa&wd=" + newVal;
//把建立好的標籤插入到body中
document.body.appendChild(script);
},
},
});
//建立一個函式aa
function aa(res) {
console.log(res, "調取介面之後返回的結果");
vm.arr = res.s;
}
</script>
</body>
</html>