选项 1:导航守卫
您可以使用所谓的Navigation Guard,它允许您在路线更新之前、之后和之后添加全局操作。您还可以使用In-component Guards将其直接添加到您的组件中,这将允许您持久化search
数据的内容。
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
类似的商店或任何商店,我强烈建议您这样做。由于您标记了类星体,我想链接到那里提供的Vuex 商店文档。您基本上可以将您的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
在您想要使用突变(未绑定到操作)保留搜索查询的组件中:
store.commit('SET_SEARCH_TERM', {
search_term: this.search // your local search query
})
如果您想在每次搜索期间持续存在,请在触发搜索 ACTION 的代码中
store.dispatch('SEARCH', {
search_term: this.search
})
访问该属性search_term
或您想调用它可以使用计算属性来完成。你也可以直接绑定状态和突变,而不需要导航守卫:
// 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/