头条新闻(vue项目实战)--搜索页
今天来实现搜索页面,首先分析一下搜索页面都要完成什么功能。第一肯定需要搜索框,在这里搜索框可以使用受控组件也可以使用非受控组件,看个人喜好。第二搜索框的下方应该有一个历史搜索记录,这个历史搜索记录可以存在localStorage中。然后我们还可以控制历史记录的显示与隐藏,当搜索框有内容时历史记录就不会展示。第三根据输入的关键字调用接口渲染数据。好了,接下来就开始实现吧!
{{ str }} {{str}} 页面效果展示:
自动获取焦点的函数:
// 封装一个自定义指令,用于搜索框自动对焦
Vue.directive('haha', {
inserted (el) {
// nodeName获取原生DOM标签的标签名,注意标签名均是大写
if (el.nodeName === 'TEXTAREA' || el.nodeName === 'INPUT') {
el.focus()
} else {
const theInput = el.querySelector('input')
const theTextArea = el.querySelector('textarea')
if (theInput) theInput.focus()
if (theTextArea) theTextArea.focus()
}
},
update (el) {
// 指令所在标签,被更新时触发
if (el.nodeName === 'TEXTAREA' || el.nodeName === 'INPUT') {
el.focus()
} else {
const theInput = el.querySelector('input')
const theTextArea = el.querySelector('textarea')
if (theInput) theInput.focus()
if (theTextArea) theTextArea.focus()
}
}
})
搜索建议结果列表
用到的接口请求:
// 获取搜索结果
export const searchResultAPI = ({ q }) => request({
url: '/v1_0/search',
params: {
q: q
}
})
// 获取搜索联想结果
export const suggestAPI = ({ q }) => request({
url: '/v1_0/suggestion',
params: {
q: q
}
})
好了,到这里搜索页功能基本完成。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!



