选项 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 Store Documentation。您基本上可以将您的 search 属性外包,并让 Store 在您的应用程序中为您持久保存它。
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/