如何使用 vue 和 vue-router 保留路由之间的某些状态

mam*_*mcx 2 vue.js vue-router quasar-framework

我有一个导航流程,其中包括

SearchPage -> ...Others or SearchPage -> ...Others or SearchPage ->
Run Code Online (Sandbox Code Playgroud)

并希望在返回时保留搜索字符串。

<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>
Run Code Online (Sandbox Code Playgroud)

现在的问题是,当用户可以导航到其他地方时,如何将查询堆栈与路由器之一关联起来。

PD 全部位于一个页面中。如果可能的话,保留屏幕而不刷新它们(但仅适用于搜索页面,直到弹出回来)会更好。

Dom*_*rer 5

选项 1:导航卫士

您可以使用所谓的导航卫士,它允许您在路线更新之前、之后和期间添加全局操作。您还可以使用组件内防护将其直接添加到组件中,这将允许您保留数据内容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
  }
}
Run Code Online (Sandbox Code Playgroud)

选项 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
Run Code Online (Sandbox Code Playgroud)

在您想要使用突变(不绑定到操作)来保留搜索查询的组件中:

store.commit('SET_SEARCH_TERM', {
  search_term: this.search // your local search query
})
Run Code Online (Sandbox Code Playgroud)

如果您想在每次搜索期间坚持下去,请在触发搜索操作的代码中

store.dispatch('SEARCH', {
  search_term: this.search
})
Run Code Online (Sandbox Code Playgroud)

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 })
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

使用前请务必了解基本概念: https: //vuex.vuejs.org/