NUXT JS动态多搜索查询参数



我是NUXT JS的新手,需要帮助。

我有一个搜索页面,其中搜索栏位于其标题组件中,该组件在页面之间共享,提交后,它转到搜索页面,搜索逻辑在商店store/search.js中完成

问题是,无论我搜索什么和参数;

  1. 我无法获得要在浏览器URL上显示的查询值,如search?Q=jump&color=yellow
  2. 由于我的搜索逻辑在商店里,我对如何从URL传递参数和像这样动态搜索感到困惑

下面是我的代码

搜索栏组件

<input type="text" class="search-input" placeholder="Search for a location" @keypress="search">
methods: {
search(event) {
const btn = event.key;
if (btn === "Enter") {
const search_terms = event.target.value;
this.$store.dispatch("search/search", search_terms);
this.$router.push('/search');
}
}
}

商店store/search.js

export const state = () => ({
result: []
})

export const mutations = {
searchTerms(state, text) {
state.searchTerms = text
},
searchResult(state, result) {
state.result = result
}
}

export const actions = {
search(vuexContext, search_terms) {
vuexContext.commit('loadingTrue')
return this.$axios
.$get('https://help.herokuapp.com/place', { params: 
{
search: 'lagos',
idealfor: ["production"],
page: 1,
limit: 12,
}
})
.then(data => {
let searchResult = data.results
vuexContext.commit('searchResult', searchResult)
})
.catch(e => {
console.log(e)
})
},
}

export const getters = {
searchResult(state) {
return state.result
},
}

我希望搜索栏显示为localhost:3000/search?search=lagos&page=1&limit=12&idealfor=["production"]

并且当链接是sg[共享并且也被访问时,将显示期望的结果。

请你在Nuxt中如何处理这件事,有人可以推荐一些资源来帮助我吗。

您可以使用$router.push将url的查询更新到包含查询的同一页面,它不会刷新页面,只更新查询。

例如:

this.$router.push('/search?search=lagos&page=1&limit=12&idealfor=["production"]');

可以使用$route.query访问查询值。如果你想在访问链接时显示结果,你需要在mounted周期中检查$route.query,并将其发送到商店以获得结果。

您可以通过创建以下操作来实现

async moveToGivenPathWithQuery({ _ }, { q = {}, color = {} }) {
// eslint-disable-next-line no-undef
await $nuxt.$router.push({ path: 'search', query: { q, color } })
},

index.vue

<template>
<div>
<button @click="moveToGivenPathWithQuery({ q: 'jump', color: 'yellow' })">
Go to search
</button>
</div>
</template>
<script>
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions('search', ['moveToGivenPathWithQuery']),
},
}
</script>

search.vue

<template>
<div>Search page</div>
</template>
<script>
export default {
mounted() {
console.log('query received', this.$route.query)
},
}
</script>

最新更新