首先要新建一个搜索页面的组件:
<div class="search-box">
<i class="icon-search"></i>
<input class="box" v-model="query" :placeholder="placeholder"/>
<i @click="clear" v-show="query" class="icon-dismiss"></i>
</div>
export default {
props: {
placeholder: {
type: String,
default: '请输入歌曲/歌手'
}
},
data () {
return {
query: ''
}
},
methods: {
clear () {
this.query = ''
}
},
created () {
this.$watch('query', (newQuery) => {
this.$emit('query', newQuery)
})
}
}
这里的placeholder和其他页面公用,所以,shiprops传入的。
<style lang="stylus" scoped>
@import "~common/stylus/variable"
.search-box
display flex
align-items center
box-sizing border-box
width 100%
padding 0 6px
height 40px
background $color-highlight-background
border-radius 6px
.icon-search
font-size 24px
color $color-background
.box
flex 1
margin 0 5px
line-height 18px
background: $color-highlight-background
color $color-text
font-size: $font-size-medium
&::placeholder
color $color-text-d
.icon-dismiss
font-size: 16px
color: $color-background
</style>
还有就是老师卖了个关子,为什么在created的时候去watch收缩框value的变化呢?
然后:search数据的抓取,这里就不写过程了,就是普通的抓取。
抓取后数据如何使用呢?
data里面定义了个hotKey
data () {
return {
hotKey: []
}
},
然后给data里面的数据赋值:
this.hotKey = res.data.hotkey.slice(0, 10)
拿到数据后,开始渲染热搜的组件
<div class="shortcut-wrapper">
<div class="shortcut">
<div class="hot-key">
<h1 class=title>热门搜索</h1>
<ul>
<li @click="addSearchValue(item.k)" v-for="item in hotKey" :key="item.n" class="item">{{item.k}}</li>
</ul>
</div>
</div>
</div>
.shortcut-wrapper
position fixed
top 178px
bottom 0
width 100%
.shortcut
height 100%
overflow hidden
.hot-key
margin 0 20px 20px 20px
.title
margin-bottom 20px
font-size: $font-size-medium
color: $color-text-l
.item
display inline-block
padding 5px 10px
margin 0 20px 10px 0
border-radius 6px
background: $color-highlight-background
font-size: $font-size-medium
color: $color-text-d
那么在search组件里面点击事件,想把item的key传到子组件怎么办?
通过使用search-box的refs来调用他内部的方法
addSearchValue (val) {
this.$refs.searchBox.setQuery(val)
},
所以,search-box内部应该是有个接口才对:
setQuery (val) {
this.query = val
}
到这里就结束了。