繁体   English   中英

我如何路由来自同一个组件的多个实例并在 vue 中保持 state

[英]how can i route multi instance that are from the same one component and keep themself state in vue

我可能无法在标题中非常准确地描述这个问题。

前提:

// in main layout page
<keep-alive>
  <router-view />
</keep-alive>

// and i have a route
{ path: "something/:id", name: "something", component: () => import("something.vue") }

然后我导航到它

this.$router.push({
          name: "something",
          params: { "id": 123, ... } // and more params
        });

到目前为止,一切正常。

但是,当我再次使用其他参数值(id 为 456)推送相同的名称时:

// something.vue

// the param is new value (456), no problem
{{$route.params.id}}
// but the other data value is kept previous route, like:
{{ count }}
<q-btn label="add" @click="add" />

<script>
export default {
  data() {
    return {
      count: 1
    };
  },
  methods: {
    add() {
      this.count++;
    }
  }
};
</script>

让我重新安排一下。

  1. 推 id 123
  2. 参数值是正确的(123),计数值为1
  3. 点击“添加”按钮,计数值为2
  4. 推送 ID 456
  5. 参数值是正确的 (456)
  6. ,!! 计数值为2,!!! 这不是我想要的

我想计数值遵循路由路径,这意味着不同路由中的所有数据 state 是独立的

当您导航到相同的路线但使用不同的参数时 - Vue 会重用组件实例,而不会先销毁然后重新创建它。 您应该使用beforeRouteUpdate钩子来捕捉这个 - 或者在$route上放置一个观察者(然后检查新路由是否仍然是相同的名称)。

更多信息在手册中 - https://next.router.vuejs.org/guide/advanced/navigation-guards.html#in-component-guards

实际上,我放弃了我的想法。

现在我尝试使用组件元素来解决

<keep-alive :include="views">
  <component :is="view" />
</keep-alive>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM