Vue cli 通过 router-link 传递道具(数据)

2022-01-25 00:00:00 vue.js vue-router vue-component

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 }
  }
}

相关文章