简述
这是一个使用vue2的搜索框小练习,实现在搜索框输入内容,敲击回车返回结果的效果。这里调用了 axios库向GitHub发送请求,并返回请求。因为是个小练习,我就往简单的做,就不用脚手架了。
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>搜索框</title>
<!-- 引入重置样式表 -->
<link rel="stylesheet" href="./css/reset.css">
<!-- 引用图标字体 -->
<link rel="stylesheet" href="./fa/css/all.css">
<!--引入Vue2-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.10/dist/vue.js"></script>
<style>
/*
使用父子相绝原理
*/
#text1{
width: 628px;
height: 1000px;
background-color: #FFFFFF;
/*确保居中*/
margin: 100px auto;
position: relative;
}
.inputshell{
width: 628px;
height: 36px;
border: 1px;
border:solid 2px #00AEEC;
border-radius: 12px;
/*参数分别代表阴影的 x y 半径 颜色*/
box-shadow: 2px 2px 5px rgba(0,0,0,3);
margin: 2px;
}
.returnData{
display: flex;
width: 580px;
flex-wrap: wrap;
background: white;
margin: 0px auto;
position: relative;
color: black;
flex-direction: column;
}
.returnData a:hover{
background-color: #0086b3;
background-size: 100%;
}
.returnData a{
width: 580px;
height: 20px;
top:12px;
left: 12px;
border: 8px;
text-decoration: none;
background: white;
font-size: 16px;
color: #212121;
/*position: relative;*/
}
button{
top:5px;
right: 0px;
width: 98px;
height: 32px;
border: none;
position: absolute;
background-color: #00AEEC;
border-radius: 5px;
}
</style>
<script src="https://cdn.bootcss.com/axios/0.18.0/axios.js" type="text/javascript"></script>
</head>
<body >
<div id="text1" >
<input type="text" class="inputshell" v-model::value="keyword" placeholder="输入关键字搜索"
@keyup.enter="getDataInfo" >
</input>
<div class="returnData" v-for="(user,index) in datalist" :key="index" >
<a :href= user.html_url>{{user.id}}</a></div>
</div>
<script type="text/javascript">
const vm =new Vue({
el:'#text1',
data:{
keyword:"",
datalist:[]
},
methods:{
getDataInfo(){
console.log("发起请求")
axios({
url:`https://api.github.com/search/users?q=${this.keyWord}`}).then(
response => {
//console.log('请求成功了',response.data.items)
//这里直接截取了数组的前十个
this.datalist = response.data.items.splice(0,10)
console.log(this.datalist[0])
},
error => {
//请求后更新List的数据
console.log('请求失败',error.message)
}
)
}
},
})
//这里监视输入内容
vm.$watch('keyword',{
handler(newvalue,oldVaule){
console.log("发生改变",newvalue)
//当清空输入框,自动把返回的结果置为0
if(newvalue.length===0){
this.datalist=[]
}
}
})
</script>
</body>
</html>
看起来有点丑,但是凑合着用也行
这里简单解释一下github的那个链接的返回每一个用户的信息: