vue和springboot实现搜索
Vue 和 Spring Boot 实现搜索功能
前端实现(Vue)
安装必要的依赖(如 axios 用于 HTTP 请求):
npm install axios
创建搜索组件(Search.vue):
<template>
<div>
<input v-model="searchQuery" @input="handleSearch" placeholder="搜索...">
<ul>
<li v-for="item in searchResults" :key="item.id">{{ item.name }}</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
searchQuery: '',
searchResults: []
};
},
methods: {
handleSearch() {
if (this.searchQuery.trim() === '') {
this.searchResults = [];
return;
}
axios.get(`http://localhost:8080/api/search?q=${this.searchQuery}`)
.then(response => {
this.searchResults = response.data;
})
.catch(error => {
console.error('搜索出错:', error);
});
}
}
};
</script>
后端实现(Spring Boot)
创建实体类(Item.java):
@Entity
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
// 其他字段和getter/setter
}
创建仓库接口(ItemRepository.java):
public interface ItemRepository extends JpaRepository<Item, Long> {
@Query("SELECT i FROM Item i WHERE i.name LIKE %:query%")
List<Item> searchByName(@Param("query") String query);
}
创建控制器(SearchController.java):
@RestController
@RequestMapping("/api")
public class SearchController {
@Autowired
private ItemRepository itemRepository;
@GetMapping("/search")
public List<Item> search(@RequestParam String q) {
return itemRepository.searchByName(q);
}
}
跨域处理
在 Spring Boot 应用中添加配置类(WebConfig.java):
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/")
.allowedOrigins("http://localhost:8081") // Vue 应用地址
.allowedMethods("*");
}
}
性能优化
对于大量数据搜索,考虑以下优化方案:
- 添加数据库索引:
@Index(name = "idx_name", columnList = "name") - 实现分页查询:在 Repository 方法中添加
Pageable参数 - 使用缓存:
@Cacheable("searchResults")
前端防抖处理
优化 Vue 组件,减少频繁请求:
<script>
import _ from 'lodash';
export default {
// ...
created() {
this.debouncedSearch = _.debounce(this.handleSearch, 300);
},
methods: {
handleSearch() {
// 原有逻辑
}
},
watch: {
searchQuery(newVal) {
this.debouncedSearch();
}
}
};
</script>






