Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
742 views
in Technique[技术] by (71.8m points)

javascript - 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
...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...