Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use addroutes method in Vue-router?

I have created a function "addroute()" to add routes dynamically,but it didn't work(the router does not changed). Is this a right way to use addRoutes method? I have learned this from tutorial. If not then give me a correct example,Thanks!

...
const Bar={
    template:'#panels',
    data(){
        return {title:'badss'}          
    }
        };
const Foo={
    template:"#panels",
        data(){
        return {title:'hell'}
    }
        };


const router = new VueRouter({
  routes:[
      {path:'/foo',component:Foo},
      {path:'/bar',component:Bar}
  ]
});

new Vue({
    el:'#root',
    router:router,
    data:{
    stats:stats
},
methods: {
    //
},

});

function addroute(){//watch here
    router.addRoutes([{path:'/ioio',component:{template:'#panels'}}])
}
setInterval("addroute()", 2000)//watch here
...
like image 544
Lauda Wang Avatar asked Sep 21 '17 10:09

Lauda Wang


People also ask

How do I create a dynamic route in vue?

Adding dynamic routes in VueUpdate the router/index. js file with the new route in the routes array. Remember to include the import for the Post component. Restart your app and head to localhost:8080/post/dynamic-routing in your browser.

How do I use my vue3 vue router?

Installing Vue Router for Vue 3 Like many frameworks, Vue has its own CLI. So at first, you need to install it using NPM or Yarn. Then you can create a new project using the vue create <project-name> command. After executing it, the CLI prompts with several options as follows.


1 Answers

The router instance that you are trying to change is already added to the Vue instance that you have. Changing that router does not update the Vue instance. What you want to do is call the router instance that you have added to the Vue instance. A complete working example can be found at: Add routes in vue-router

So you access the router inside a method in the Vue instance using this.$router. You then add the desired route that you want to add using the .addRoutes functionality.

In the fiddle, you can see that I have added the ioio link in the HTML already, but it does not work yet (clicking it will result in the <span>Default</span> being added to the <router-view></router-view>). When clicking on the button, you are adding a new route. I have added the this.$router.push('/ioio'); to force an update on the <router-view></router-view> after adding the route. If you remove this line of the code, the <router-view></router-view> will display the last shown element (which is desirable in most cases), and clicking on the ioio-button again will show the newly created route.

Hope this helps!

like image 84
IvorG Avatar answered Oct 12 '22 08:10

IvorG