我有一个导航流程,其中包括
SearchPage -> ...Others or SearchPage -> ...Others or SearchPage ->
并且想在返回时保留搜索字符串。
<template id="ListCustomersPage">
<q-layout>
<q-layout-header>
<toolbar :title="title" :action="doCreate" label="New"></toolbar>
<q-search inverted placeholder="Type Name, Code, Nit, Phone Number or Email" float-label="Search" v-model="search" />
<q-btn icon="search" color="secondary" @click="doSearch" />
</q-layout-header>
</q-layout>
</template>
现在的问题是,当用户可以导航到其他地方时,如何将查询堆栈与路由器之一关联起来。
P.D 全部都在一个页面中。如果可能的话,保持屏幕不刷新(但仅限搜索页面,直到弹出)会更好。
最佳答案
选项 1:导航 guard
您可以使用所谓的 Navigation Guard它允许您在路线更新之前、之后和期间添加全局操作。您还可以使用 In-component Guards 将其直接添加到您的组件中,这将允许您保留搜索
数据的内容。
const VueFoo = {
// I guess your search attribute is in your data
data() {
return {
search: ''
}
},
mounted() {
// retrieve your information from your persistance layer
},
beforeRouteLeave (to, from, next) {
// called when the route that renders this component is about to
// be navigated away from.
// has access to `this` component instance.
// persist this.search in localstorage or wherever you like it to be stored
}
}
选项 2:使用 (Vuex) 存储
如果您能够添加 Vuex Store
或任何类似的 Store,我强烈建议您这样做。既然你标记了类星体,我想链接到 Vuex Store Documentation那里提供。您基本上可以外包您的 search
属性,并让应用商店在您的应用程序中为您保留它。
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
search_term: ''
},
mutations: {
SET_SEARCH_TERM (state, payload) {
state.search_term = payload.search_term
}
},
actions: {
SEARCH ({ commit, state }, payload) {
commit('SET_SEARCH_TERM', payload.search_term)
// your api call to search which can also be stored in the state
}
}
})
export default store
在您想要使用突变(不绑定(bind)到操作)来保留搜索查询的组件中:
store.commit('SET_SEARCH_TERM', {
search_term: this.search // your local search query
})
如果您想在每次搜索期间保留,请在触发搜索操作的代码中
store.dispatch('SEARCH', {
search_term: this.search
})
访问属性search_term
或者您想要调用它的方式可以使用计算属性来完成。您还可以直接绑定(bind)状态和突变,而根本不需要导航防护:
// your Vue component
computed: {
search: {
get () {
return this.$store.state.search_term
},
set (val) {
this.$store.commit('SET_SEARCH_TERM', { search_term: val })
}
}
}
使用前请务必了解基本概念:https://vuex.vuejs.org/
关于vue.js - 如何使用 vue 和 vue-router 保留路由之间的某些状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52487836/