Basic example add routes

Vue router example with add routes

by simati

HTML

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id='root'>
  <ul>
    <router-link to='/foo'>Foo</router-link>
    <router-link to='/bar'>Bar</router-link>
    <router-link to='/ioio'>Ioio</router-link>
    <pre>{{ $route }}</pre>
  </ul>
  <button v-on:click='addRoute'>
    Add route
  </button>
  <router-view></router-view>
</div>

JavaScript

const Default = {
  template: '<span>Default</span>',
};
const Bar = {
  template: '<span>Bar</span>',
};
const Foo = {
  template: "<span>Foo</span>",
};

const router = new VueRouter({
  routes: [{
    path: '/foo',
    component: Foo
  }, {
    path: '/bar',
    component: Bar
  }, {
    path: '/',
    component: Default
  }, {
    path: '*',
    redirect: '/'
  }, 
  {
          path: '/ioio',
          name: 'new',
          component: {
            template: '<span>Ioio</span>'
          }
        }]
});

new Vue({
  el: '#root',
  router: router,
  methods: {
    addRoute: function() {
    	const rdm = Math.random()
      this.$router.addRoutes(
        [{
          path: '/' + rdm,
          name: rdm,
          component: {
            template: `<span>${this.$route.path}</span>`
          }
        }]);
        console.log(this.$router)
      this.$router.push('/' + rdm);
    },
  },
});