Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS - updating URL with dynamic data

I have a single page VueJS app with a number of data variables I want to encode into the URL.

As an example if my route configuration is (I'm not sure if the syntax is correct):

routes: [
    {
        path: '/:foo/:bar/:oof/:rab',
        component: App
    }

And the Component is:

<script>
export default {
  name: "App",
  data: function() {
    return {
      foo: 1,
      bar: 2,
      oof: 3,
      rab: 4
    }
  }
}

Then the URL would be http://www.example.com/#/1/2/3/4

And if foo is changed to 9999 the URL would automatically update: http://www.example.com/#/9999/2/3/4

It would also respond to the user changing the URL, or opening the app with a different URL by loading the URL values into the data.

I thought this would be relatively straightforward but after a Google I'm utterly confused by the correct way of going about this.

Any help/ examples/ solutions greatly appreciated.

like image 445
BaronGrivet Avatar asked Sep 13 '18 02:09

BaronGrivet


1 Answers

Whatever you use to change the values would need to trigger a route push. For example

methods: {
  changeFoo (newFoo) {
    // you can set foo but it probably won't matter because you're navigating away
    this.foo = newFoo
    this.$router.push(`/${newFoo}/${this.bar}/${this.oof}/${this.rab}`)
  }

See https://router.vuejs.org/guide/essentials/navigation.html


It might be easier if you name your route, eg

routes: [{
  name: 'home',
  path: '/:foo/:bar/:oof/:rab',
  component: App
}]

then you could use something like

this.$router.push({name: 'home', params: this.$data})
like image 50
Phil Avatar answered Nov 09 '22 22:11

Phil