实现搜索,然后返回结果
这里用到了同级通信,以及发送请求,以及map的使用
1.Ajax请求的位置,放在Main中,因为无论是在发送请求前后都要更新Main中的状态
2.兄弟间的通信要么用props给父组件,再传递给子组件,要么就用PubSub订阅与发布来做,用这个首先得想清楚,发布是传递一个值,所以在这你可以想成把搜索框的值传递到Main中,来实现url的变化
3.map的使用,一对一,不用过滤,这里map的使用注释有注解,用()包了一下,返回的object对象,不用return
//App
<template>
<div id="app">
<div class="container">
<Search/>
<users-main/>
</div>
</div>
</template>
<script>
import Search from './components/Search'
import Main from './components/Main'
export default {
components:{
Search,
UsersMain:Main
}
}
</script>
<style scoped>
</style>
//Main
<template>
<div>
<h2 v-if="firstView">输入用户名搜索</h2>
<h2 v-if="loading">LOADING...</h2>
<h2 v-if="errorMsg">{{errorMsg}}</h2>
<div class="row">
<div class="card" v-for="(user, index) in users" :key="index">
<a :href="user.url" target="_blank">
<img :src="user.avatar" style='width: 100px'/>
</a>
<p class="card-text">{{user.name}}</p>
</div>
</div>
</div>
</template>
<script>
import PubSub from 'pubsub-js'
import axios from 'axios'
export default {
data(){
return{
firstView:true,
loading:false,
users:null,//[{url:'', avatar:'', name:''}]
errorMsg:''
}
},
mounted() {
//是否在此处发送ajax请求,不是,而是在点击search之后
//订阅搜索消息
PubSub.subscribe('search', (msg, searchName) => {//说明去要发送Ajax请求去搜索
const url = `https://api.github.com/search/users?q=${searchName}`
//更新状态(请求中)
this.firstView = false
this.loading = true
this.users = null
this.errorMsg = ''
//发ajax请求
axios.get(url).then(
response =>{
const result = response.data
//arr.map(item =>({ })),{}里是object的形式,返回object,也不加return。
const users = result.items.map(item => ({
url:item.html_url,
avatar:item.avatar_url,
name:item.login
}))
//成功,更新状态(成功)
this.loading = false
this.users = users
}).catch(error => {
//失败,更新状态(失败)
this.loading = false
this.errorMsg = '请求失败'
})
})
}
}
</script>
<style scoped>
.card {
float: left;
width: 33.333%;
padding: .75rem;
margin-bottom: 2rem;
border: 1px solid #efefef;
text-align: center;
}
.card > img {
margin-bottom: .75rem;
border-radius: 100px;
}
.card-text {
font-size: 85%;
}
</style>
//Search
<template>
<section class="jumbotron">
<h3 class="jumbotron-heading">Search Github Users</h3>
<div>
<input type="text" placeholder="enter the name you search" v-model="searchName"/>
<button @click="search">Search</button>
</div>
</section>
</template>
<script>
import PubSub from 'pubsub-js'
export default {
data(){
return{
searchName:'',
}
},
methods:{
search(){
const searchName = this.searchName.trim()
if (searchName){
//如果有值,搜索发布消息
PubSub.publish('search', searchName)
}
}
}
}
</script>
<style scoped>
</style>
这里想不用点击确认 在输入或者删除的时候就自动的发送请求更改 没想出来
后来最后放弃的时候想出来了,没那么麻烦,一开始还想get set啥的,其实在这加一个keyup事件就好了嘛