【问题标题】:VueJs - Passing data to subRoutes component with vue-routerVueJs - 使用 vue-router 将数据传递给 subRoutes 组件
【发布时间】:2016-10-19 07:48:37
【问题描述】:

我不明白如何将“路由组件”加载的数据传递给“子路由组件”.. (我使用 Vue.js 和 Vue-router)

我的路由器是这样的:

router.map({
  '/a': {
    component: A,
    subRoutes: {
      '/b': {
        component: B
      },
      '/c': {
        component: C
      }
    }
  }
});

我只想将组件 A 加载的数据与组件 B 和 C 共享。

提前致谢!

【问题讨论】:

标签: vue.js vue-router


【解决方案1】:

你有两个简单的选择。

丑陋的

使用子路由组件中的$parent 选项。这使您可以访问父实例,这不是推荐的方式,但它很有效

// from the child component
this.$parent.someData

好的

使用props。道具让您有机会将任何数据从父母传递给孩子。更好,因为可以防止错误(您传递数据而不是实例)并且您只传递您需要的内容,即使它不是父数据的一部分。

// parent component
<template>
    <child :childsdata="parentdata"></child>
</template
<script>
    export default {
        data: function () {
            return {
                parentdata: 'Hello!'
            }
        }
    }
</script>

// child component
<template>
    {{ childsdata }} <!-- prints "Hello!" -->
</template>
<script>
    export default {
        props: {
            childsdata: {
                type: String
            }
        }
    }
</script>

【讨论】:

  • 可以使用 props 从component Bcomponent C 发送数据吗?
  • 我在很多地方都发现了这个“”风格的答案,但是你在 vue-router 下看到没有 只有 我不想添加道具,因为每个溃败都需要一组不同的道具。这应该是 vue-router 使用的路由对象的一部分。
猜你喜欢
  • 2018-10-21
  • 2021-12-31
  • 2019-12-29
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
  • 2018-09-12
  • 2019-10-07
  • 2016-09-24
相关资源
最近更新 更多