search

Home  >  Q&A  >  body text

javascript - How to use vue components to dynamically generate router-link

Vue.component('sidebar',
    {template:'<p><router-link to="/">Go to Foo</router-link><router-link to="/bar">Go to Bar</router-link></p>'}
)
var sidebar = new Vue({el: '#sidebar'})

// 加载router

$('head').append('<script src="https://cdn.bootcss.com/vue-router/2.6.0/vue-router.js"></script>')

//之后再执行VueRouter

Current Issues

Although this is feasible, an error that the component is not registered will be reported before vue-router is executed. I would like to ask you if there is a better dynamic implementation method

Original question↓

As shown above, it is necessary to dynamically generate side routes, and then execute vue-router to parse, but an error will occur. I cannot understand why the error occurred

The reason is that vue-router will automatically parse router-link, even if there is no VueRouter instance

过去多啦不再A梦过去多啦不再A梦2832 days ago961

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-06-26 10:55:30

    1. First of all, the second parameter of Vue.component is a configuration object. Your way of writing it does not even comply with JS syntax.

    2. Secondly, the template configuration should be a string of HTML code, so change it to:

    Vue.component('sidebar', {
        template: '<p><router-link to="/">Go to Foo</router-link><router-link to="/bar">Go to Bar</router-link></p>'
    });

    Update

    (Reference: https://router.vuejs.org/en/e...)

    In view of the situation where you mentioned the introduction, the code is modified as follows:
    First introduce Vue and Vue-router in the following order

    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

    Then add the following JS

    // 在Vue里面注册VueRouter,这样可以在Vue里面使用`<router-link>`
    Vue.use(VueRouter);
    
    // 下面这一段是路由设置和应用根元素绑定,具体可以参照官方文档
    // -----------------------------------
    var routes = [ ... ]; // 这个是路由的配置,你自己写
    
    // 定义路由VueRouter控件,其中,`{routes}`是`{routes: routes}`的简写,可能是ES6里面的新语法
    var router = new VueRouter({routes});
    
    // 创建Vue对象
    var app = new Vue({
        el: '#app', // 假设绑定的根元素为#app
        router, // 此处也是简写
    });

    Then you can use the Vue.component() statement. At this time, because the Vue-Router component is registered, <router-link> can be recognized.

    reply
    0
  • Cancelreply