Home > front end >  How to implement permalinks in a serverless Vue SPA
How to implement permalinks in a serverless Vue SPA

Time:04-04

I made this little app which is a simple Vue serverless SPA. I wish to pass an array of strings and a an array of numbers through the URL so that I can share "states" of the websites with colleagues. I understand vue-routercan update the route's parameters as per their documentation, but I do not have enough perspective to see how to implement this to solve my problem. I would love some help or guidance so I actually learn from this. Thank you all.

EDIT: after Mr. Luis Brito's hint. I added the following to my code (props)

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'home',
      component: require('@/views/Home').default,
      props: { myNumbers: [1,2,3]}
    },
  ]
})

in a component I did

mounted () {
  this.$router.push({ name: 'myNumbers', params: {myNumbers: [1,2,3,4] }})
  const myNumbers = this.$route.params.myNumbers
  console.log(myNumbers);
}

But now my App throws a Vue-Router error [vue-router] Route with name 'myNumbers' does not exist but it does console log the numbers I pushed. Is it possible to make my app look for props and only if they are there to do something with them? Otherwise I get a white screen.

CodePudding user response:

The way I see to solve this problem is use vue-router with a route that passes props to the component, that prop can be an object containing the two arrays that you mentioned.

Referer to Vue Router - Obect Mode

Here is an example for the router:

const routes = {
  path: '/promotion/from-newsletter',
    component: Promotion,
    props: { myNumbers: [1,2,3,5,8], myStrings: ['first', 'second', 'third'] 
  }
}

On the component side, you can access those props on created() lifecycle hook, or mounted()

mounted() {
  const myNumbers = this.$route.params.myNumbers
  const myStrings = this.$route.params.myStrings
}

EDITED

TO pass the values programatically, would be better to use Function Mode to capture the URL params and pass it to component. Another way would be to create a component where you can input the numbers and strings that you want, and then call the router and pass those values to the route for the final destination component.

  • Related