vue实现搜索跳转功能
Vue 实现搜索跳转功能的方法
使用 Vue Router 实现搜索跳转
在 Vue 项目中,可以通过 Vue Router 的 push 方法实现搜索跳转。创建一个搜索框,监听用户输入,触发路由跳转。
<template>
<div>
<input v-model="searchQuery" @keyup.enter="handleSearch" placeholder="输入搜索内容" />
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: ''
}
},
methods: {
handleSearch() {
if (this.searchQuery.trim()) {
this.$router.push({ path: '/search', query: { q: this.searchQuery } })
}
}
}
}
</script>
在路由配置中定义搜索页
确保路由配置中包含搜索页的路由,以便接收搜索参数。
const routes = [
{
path: '/search',
name: 'Search',
component: SearchPage,
props: (route) => ({ query: route.query.q })
}
]
在搜索页接收参数并处理
在搜索页组件中,通过 props 接收搜索参数,并进行后续处理(如调用 API 获取搜索结果)。
<template>
<div>
<h1>搜索结果: {{ query }}</h1>
</div>
</template>
<script>
export default {
props: ['query'],
watch: {
query(newVal) {
this.fetchResults(newVal)
}
},
methods: {
fetchResults(query) {
// 调用 API 获取搜索结果
console.log('搜索关键词:', query)
}
}
}
</script>
使用 Vuex 管理搜索状态
如果需要全局管理搜索状态,可以使用 Vuex 存储搜索历史和当前搜索关键词。
const store = new Vuex.Store({
state: {
searchHistory: [],
currentQuery: ''
},
mutations: {
setCurrentQuery(state, query) {
state.currentQuery = query
state.searchHistory.push(query)
}
}
})
在组件中调用 Vuex
在搜索框组件中,提交 mutation 以更新搜索状态。
methods: {
handleSearch() {
if (this.searchQuery.trim()) {
this.$store.commit('setCurrentQuery', this.searchQuery)
this.$router.push({ path: '/search', query: { q: this.searchQuery } })
}
}
}
优化搜索体验
可以通过防抖(debounce)减少频繁搜索请求,提升性能。
import { debounce } from 'lodash'
methods: {
handleSearch: debounce(function() {
if (this.searchQuery.trim()) {
this.$router.push({ path: '/search', query: { q: this.searchQuery } })
}
}, 500)
}
以上方法可以根据实际需求组合使用,灵活实现 Vue 中的搜索跳转功能。







