【问题标题】:How to pass data to vue router router-view?如何将数据传递给Vue路由器路由器视图?
【发布时间】:2019-04-01 17:46:36
【问题描述】:

我正在使用 Vue 路由器。在我以前的代码中:

<div v-bind:is="page.component_name" v-bind:page="page"></div>

哪个有效,page 数据已传递给组件。但是我如何对路由器视图做同样的事情呢?这似乎不起作用:

<router-view v-bind:page="page"></router-view>

js:

var vm = new Vue({
    ...,
    router : new VueRouter({
        routes : [
            { path: '/foo', component: { template: '<div>foo</div>', created:function(){alert(1);} } },
            //{ path: '/bar', component: { template: '<div>bar</div>', created:function(){alert(2);} } },
            { path: '/bar', component: Vue.component("ti-page-report") }
        ]
    }),
     ...
});

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vue-router


    【解决方案1】:

    vue-router 在文档中有一个专门的页面,介绍如何将道具传递给router-view

    Passing Props to Route Components

    文档中的示例 sn-p:

    const router = new VueRouter({
      routes: [
        { path: '/user/:id', component: User, props: true },
    
         // for routes with named views, you have to define the `props` option for each named view:
        {
          path: '/user/:id',
          components: { default: User, sidebar: Sidebar },
          props: { default: true, sidebar: false }
        }
      ]
    })
    

    如果您正在寻找简化的用法,props 仍然可以像传递给任何组件的方式一样传递。但是用于渲染路由的组件(在路由定义中指定的组件)应该会收到 props。

    这是将props 传递给router-view 的简单用法示例:

    【讨论】:

    • 我将如何设置它,以便我可以在组件中访问page.icon
    • 示例代码令人困惑,因为它没有显示如何从组件访问 prop 值。
    • 我在答案中添加了简化的用法示例。请检查title 属性传递给&lt;router-view&gt; 的方式。这对您的问题有帮助吗?
    • 在我的例子中,:title="...", ... 是一个函数,它根据需要首先发生的点击事件获取正确的数据,但是路由器“ " 之前发生,然后我收到一堆关于未定义值的控制台错误。
    • nvm 我用这个github.com/vuejs/vue-router/issues/800解决了它
    【解决方案2】:

    需要访问正在发送的props的组件(“ti-page-report”)只需添加即可:

    <template>
      <div>
        <h1>Now you can access page: {{ page }}</h1>
      </div>
    </template>
    
    export default {
      name: "TiPageReport",
      props: ['page'], // can now be accessed with this.page
      ...
    };
    

    如何正确使用道具,请参阅https://vuejs.org/v2/guide/components-props.html

    【讨论】:

      猜你喜欢
      • 2023-04-03
      • 2018-09-16
      • 2021-12-28
      • 2020-05-10
      • 2017-03-06
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 2013-04-15
      相关资源
      最近更新 更多