如何在Vue-router中使用addroutes方法? [英] How to use addroutes method in Vue-router?

查看:1326
本文介绍了如何在Vue-router中使用addroutes方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个函数addroute()来动态添加路由,但它不起作用(路由器没有改变)。
这是使用addRoutes方法的正确方法吗?我从教程中学到了这一点。
如果没有,请给我一个正确的例子,谢谢!

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
...


推荐答案

您尝试更改的路由器实例已添加到您拥有的Vue实例中。更改该路由器不会更新Vue实例。您要做的是调用已添加到Vue实例的路由器实例。可以在以下位置找到完整的工作示例:在vue-router中添加路由

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

所以你使用这个来访问Vue实例中方法内的路由器。$ router 。然后,使用 .addRoutes 功能添加要添加的所需路由。

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.

在小提琴中,你可以看到我已经在HTML中添加了ioio链接,但它还没有工作(点击它会产生< span>默认< / span> 被添加到< router-view>< / router-view> ) 。单击按钮时,您将添加新路线。我添加了这个。$ router.push('/ ioio'); 来强制更新< router-view><添加路由后,/ router-view> 。如果您删除此行代码,< router-view>< / router-view> 将显示最后显示的元素(在大多数情况下是理想的) ,再次点击ioio按钮将显示新创建的路线。

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.

希望这会有所帮助!

这篇关于如何在Vue-router中使用addroutes方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆