簡體   English   中英

VueJS vue-router 將值傳遞給路由

[英]VueJS vue-router passing a value to a route

在帶有 vue-router 2 的 VueJS 2 中,我使用帶有子組件的父視圖,如下所示:

帶有路由 /widget_container/ 的 WidgetContainer.vue:

<template>
  <component :is="activeComponent"></component>
</template>

<script>
  import WidgetA from './components/WidgetA'
  import WidgetB from './components/WidgetB'

  export default {
    name: 'WidgetContainer',
    components: {
      WidgetA,
      WidgetB
    },
    data () {
      return {
        activeComponent: 'widget-a'
      }
    }
  }
</script>

在 WidgetA 我可以選擇一個小部件 id

<template>
// v-for list logic here..
<router-link :to="{ path: '/widget_container/' + widget.id }"><span>{{widget.name}}   </span></router-link>
</template>

<script>
    export default {
    name: 'WidgetA',
    data() {
      return {
        widgets: [
          { id: 1,
            name: 'blue-widget'
          }]}}

路線.js:

export default new Router({
  routes: [
    {
      path: '/widget_container',
      component: WidgetContaner
    },
    {
      path: '/widget_container/:id?',
      redirect: to => {
        const { params } = to
        if (params.id) {
          return '/widget_contaner/:id'
        } else {
          return '/widget_container'
        }
      }
    }]})

如果路由是 /widget_container/1(其中 '1' 是在 WidgetA 中選擇的 id),則從 WidgetContainer 我想渲染 WidgetB,但我無法解決:

1)如何將選定的小部件 id 傳遞到 WidgetA 中的路由器鏈接 2)如何在 WidgetContainer 中知道路由是 /widget_contaner/1 而不是 /widget_container/ 並相應地渲染 WidgetB。

有任何想法嗎?

使用 Vuex 不是更容易、更可擴展嗎? 只需將 id 提交到存儲而不是導航?

您可以通過發出事件將數​​據傳遞給父級,您可以在此處此處查看更多詳細信息。

數據更改后,您可以監視它並更新存儲小部件的變量。

另一種選擇是,如果組件之間的通信隨着時間的推移變得無法管理,則可以使用一些中央狀態管理,例如vuex ,更多細節可以在這里找到。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM