Vue, is there a way to pass data between routes without URL params?

KasparTr picture KasparTr · Jun 23, 2018 · Viewed 25.3k times · Source

I am looking how to pass data secretly between two separate components (not parent and child) without using URL params in my Vue2 app. This doesn't mean I am passing secrets but rather I just dont want the user to see it (only for UI considerations).

I know Vue has Props but they are meant for passing data between parent and child component. In my case, my URL will change but I don't want to pass data via visible params.

Someone claimed to use props without URL params here but I haven't been able to reproduce a working solution (getting undefined each time).

I also checked out these options but they are all using either URL or query params which as we know are visible.

An ugly solution would be to write the data to local storage and then read it there but this creates a lot of overhead and complexity (like what if I only want this data to be read once, etc).

Is there a more elegant solution to this problem?

Thanks!

Answer

mayank1513 picture mayank1513 · Jul 11, 2018
  1. make props: true for the destination route -- in the index.js file of router

    {
      path: '/home',
      name: 'home',
      component: taskChooser,
      props: true,
      }

  1. define prop in the component e.g props: ['myprop'], - note the quotes

  2. copy the variable you want to pass from the source route into the same name as your prop - in this case myprop

myprop = theVariableThatYouWantToPass

this.$router.replace({name:'home', params:{myprop}});

Make sure that the name of prop and variable are same - the prop is in quotes.

It's working for me.