Vue cli 通过 router-link 传递道具(数据) [英] Vue cli passing props (data) through router-link

查看:36
本文介绍了Vue cli 通过 router-link 传递道具(数据)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I am using Vue-cli with vue-router installed, inside my App.vue I've got <router-link to="/about" >About</router-link> in which it's going to display the content of about component on click. Now, I would like to pass props data to About.vue component from `` App.vue. Adding :myprops="myprops" inside <router-link to="/about" :myprops="myprops">About</router-link> didn't work that's why I add the following to App.vue :

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

Inside About.vue component I did props:['myprops'] to get the props data and by using {{myprops}} to display it. Now, if inside App.vue, I add <my-about :myprops="myprops"></my-about> then the props data will be handed over to About.vue and will be display but the content of About.vue also will be display on my App.vue page and also, it is going to repeat itself inside About.vue. I don't want that. I just need to pass the myprops data to About.vue component without displaying the About.vue content inside App.vue. And, this is my path code inside router/index.js for reference: { path: '/about', component: About }

How can I be able to do that?

解决方案

A Router is not meant to be used to pass data around. It's meant to map URLs to coponents. So what you can do is to pass the props in the URL, as params or query parameters. (If hat doesn't suit your requirements, you will likely need a real state management solution like Vuex)

A Param has to be defined in the route definition (see here) and it seems you don't want that.

You can pass the info as a query parameter, the link looks like this:

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

The resulting URL will end up looking like this:

/about?myprop=somevalue

Then, this query parameter is available as this.$route.query.myprop in any component. To pass it as an actual prop to the About component specifically, you need to configure the router to do so:

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

这篇关于Vue cli 通过 router-link 传递道具(数据)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆