Vuejs 搜索功能无法正常工作
2021-09-21
616
我的导航栏组件中有一个搜索栏,使用 Axios,我可以过滤文章。
export default {
data() {
return {
articles: [],
article: {},
search: '',
}
},
methods: {
getArticles() {
const url = `${baseApiUrl}/search?search=${this.search}`;
axios(url).then((res) => {
this.articles = res.data;
});
}
},
watch: {
search() {
const route = {
name: 'searchArticles'
}
if(this.search !== '') {
route.query = {
search: this.search
}
}
},
'$route.query.search': {
immediate: true,
handler(value) {
this.search = value
}
}
},
};
</script>
<template>
<header class="navbar">
<form class="searchInput">
<input v-model="search" @keyup.enter="getArticles()" placeholder="Search..." />
<router-link :to="{ path: '/search', query: { search: this.search }}">
<button type="submit">
<font-icon class="icon" :icon="['fas', 'search']"></font-icon>
</button>
</router-link>
</form>
</header>
</template>
我有 searchResult 组件来呈现搜索结果。
export default {
data() {
return {
articles: [],
article: {},
search: ''
}
},
created() {
const url = `${baseApiUrl}/search?search=${this.search}`;
axios(url).then((res) => {
this.articles = res.data;
});
},
watch: {
search() {
const route = {
name: 'searchArticles'
}
if(this.search !== '') {
route.query = {
search: this.search
}
}
},
'$route.query.search': {
immediate: true,
handler(value) {
this.search = value
}
}
},
};
</script>
<template>
<div>
<div class="result-search">
<ul>
<li v-for="(article, i) in articles" :key="i">
<ArticleItem :article="article" />
</li>
</ul>
</div>
</div>
</template>
当我第一次搜索时,它会带我到 /search?... 并显示搜索结果,但如果我在字段中输入另一个值,我的 URL 就会从 /search?search=a 更改为 /search?search=b,结果仍然是搜索 A,只有当我重新加载页面时,它才会给我带来搜索 B 的结果。 为什么会这样? 我的所有内容都通过
我的应用组件:
<template>
<div id="app">
<Header :hideUserDropdown="!user" />
<Loading v-if="validatingToken" />
<Content v-else />
<Footer />
</div>
</template>
集中在我的内容组件中
1个回答
用于搜索数据的 axios 调用当前存在于您的
created
钩子中。这意味着它将仅在该页面/组件的初始加载时运行。
将您的搜索功能移到方法中并从您的观察器中调用它,即
watch: {
'$route.query.search': {
immediate: true,
fetchArticles(value)
}
},
methods: {
async fetchArticles(val) {
let url = `${baseApiUrl}/search?search=${val}`
try {
let res = await axios(url)
this.articles = res.data
} catch (error) {
console.log(`An error occurred attempting to fetch articles with search term of ${val}: `, error)
} finally {
// do something here if you need
}
}
}
如果您遇到困难,Vue 文档非常有用。这是 Vue 生命周期钩子的链接以及何时可以使用它们 :)
RuNpiXelruN
2021-09-21