个人博客,导航栏搜索功能完善
注意:搜索栏的位置。
要在前端合理的分配导航栏的位置。
前端代码:
BaseHeader.vue:
<el-col :span="6">
<el-menu mode="horizontal" active-text-color="#5FB878">
<el-menu-item>
<template>
<el-autocomplete v-model="search" :fetch-suggestions="querySearchAsync" placeholder="请输入内容"
@select="handleSelect">
</el-autocomplete>
</template>
</el-menu-item>
</el-menu>
</el-col>
import {searchArticle} from '@/api/article'
data() {
return {
search:'',
articles:[]
}
},
methods: {
logout() {
let that = this
this.$store.dispatch('logout').then(() => {
this.$router.push({ path: '/' })
}).catch((error) => {
if (error !== 'error') {
that.$message({ message: error, type: 'error', showClose: true });
}
})
},
querySearchAsync(queryString,cb){
searchArticle(this.search).then((res)=>{
if(res.success) {
var results = [];
for(const item of res.data){
results.push({id:item.id,value:item.title});
}
cb(results);
}
})
},
handleSelect(item){
this.$router.push({path:'/view/'+item.id})
}
}
}
article.js:
export function searchArticle(search) {
return request({
url: `/articles/search`,
method: 'post',
data:{"search": search}
})
}
后端代码:
controller:
/**
* 首页搜索功能
* @param articleParam
* @return
*/
@PostMapping("search")
public Result search(@RequestBody ArticleParam articleParam){
String search = articleParam.getSearch();
return articleService.searchArticle(search);
}
articleParam:
@Data
public class ArticleParam {
private Long id;
private ArticleBodyParam body;
private CategoryVo category;
private String summary;
private List<TagVo> tags;
private String title;
private String search;
}
ArticleService:
/**
* 搜索功能
* @param search
* @return
*/
Result searchArticle(String search);
ArticleServiceImpl:
/**
* 搜索功能
* @param search
* @return
*/
@Override
public Result searchArticle(String search) {
LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//根据查看数量进行倒叙排序
queryWrapper.orderByDesc(Article::getViewCounts);
queryWrapper.select(Article::getId,Article::getTitle);
queryWrapper.like(Article::getTitle,search);
List<Article> articles = articleMapper.selectList(queryWrapper);
return Result.success(copyList(articles,false,false));
}