Vue CLI通过路由器链接传递道具(数据)

时间:2018-07-09 11:39:24

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

我正在使用Vue-cli,安装了vue-router,在我的App.vue里面,我有<router-link to="/about" >About</router-link>,它将在单击时显示关于组件的内容。现在,我想将道具数据从``App.vue.com传递到About.vue组件。在<router-link to="/about" :myprops="myprops">About</router-link>内添加:myprops =“ myprops”无效,这就是为什么我在App.vue中添加以下内容:

<script>
import About from './components/About.vue';
export default {
  name: 'App',
 components:{'my-about':About}
  data(){return {...}
  },
props:{myprops:[{.....}]}
}
</script>

About.vue组件内部,我做了props:['myprops']来获取道具数据,并使用{{myprops}}来显示道具数据。 现在,如果在App.vue中添加了<my-about :myprops="myprops"></my-about>,则道具数据将移交给About.vue并显示,但About.vue的内容也将显示在我的App.vue页,并且还将在About.vue内重复。我不要我只需要将myprops数据传递给About.vue组件,而无需在About.vue内显示App.vue内容。 而且,这是我在router/index.js中的路径代码,以供参考: { path: '/about', component: About }

我该怎么做?

2 个答案:

答案 0 :(得分:1)

路由器不用于传递数据。这是为了将URL映射到组件。因此,您可以做的是在URL中传递参数,作为参数或查询参数。 (如果帽子不符合您的要求,您可能需要像Vuex这样的真实状态管理解决方案)

必须在路由定义(see here)中定义参数,看来您不希望如此。

您可以将信息作为查询参数传递,链接如下所示:

<router-link :to="{ path: '/about', query: { myprop: 'someValue' }}">
  About
</router-link>

生成的URL最终看起来像这样:

/about?myprop=somevalue

然后,此查询参数在任何组件中都可以作为this.$route.query.myprop使用。要将其作为实际道具具体传递到About组件,您需要configure the router to do so

{
  path: '/about', 
  component: About,
  props(route) {
    return {  myprop: route.query.myprop }
  }
}

答案 1 :(得分:0)

我认为您不是Vue的初学者。

1 -在目标组件上定义道具

export default {
    name: "MyComponent",
    props: {
        exampleProp: Object
    }
}

2 -使用 props:true

定义一条路线
...
    routes: [
        {
            path: '/mycomponent',
            name: 'MyComponent',
            component: MyComponent,
            props: true
        },
...

3 -在路由器链接上使用路由名称而不是路径,并将porps作为参数传递

<router-link 
   :to="{ name: 'MyComponent', 
          params: { exampleProp: examplePropValue }}">
Link to My Component
</router-link>
相关问题