将 vue-router 组件解释为一个函数

explain vue-router component as a function

我在几个不同的地方看到过以下类型的路由定义:

{   path : '/dashboard',
    component: { render (c) { return c('router-view') }},
    children:[{
            path:"",
            component: Dashboard
        }]
},    

我想了解这与

有何不同
{   path : '/dashboard',
    component: Dashboard
},    

我认为这与可选添加的子路径有关(例如 /dashboard/user),因此这里的子数组只是说明 Dashboard 组件呈现路径 /dashboard 而如果我有第二个代码然后它只能呈现 /dashboard.

我想知道的是这到底是做什么的

    component: { render (c) { return c('router-view') }},

我认为这是某种形式的退化组件,但我不明白它到底做了什么以及如何做。

我不知道您的其余代码,但看起来这可能是 vue-router Lazy Loading functionality 的一个实现。基本上,Vue + Webpack 将把你的代码分成块,并且只在用户尝试导航到这些路由时加载这些块,而不是加载它们并创建一个比必要更大的包来下载。

When building apps with a bundler, the JavaScript bundle can become quite large, and thus affect the page load time. It would be more efficient if we can split each route's components into a separate chunk, and only load them when the route is visited.

Combining Vue's async component feature and webpack's code splitting feature, it's trivially easy to lazy-load route components.

在 Vue 中,组件是使用包含其配置的对象创建的。

最简单的组件可能看起来像这样

componentConfig = {
    template: '<div>test</div>'
};    
Vue.component('test', componentConfig);

在某些情况下,开发人员可能不想使用 template,而是希望使用纯 Javascript 从头开始​​创建元素。这就是渲染函数的用武之地。

Vue recommends using templates to build your HTML in the vast majority of cases. There are situations however, where you really need the full programmatic power of JavaScript. That’s where you can use the render function, a closer-to-the-compiler alternative to templates.

from https://vuejs.org/v2/guide/render-function.html#Basics

要将上面的示例更改为使用渲染函数:

componentConfig = {
    render: function(createElement) {
        return createElement('div', 'test')
    }
};
Vue.component('test', componentConfig);

它们会产生完全相同的结果:

换句话说,render function 只是 template.

的替代方法
{
    component: {
        render(c) {
            return c('router-view')
        }
    }
}

等于

{
    component: {
        render(createElement) {
            return createElement('router-view')
        }
    }
}

等于

{
    component: {
        template: `<router-view></router-view>`
    }
}

因为渲染函数是 closer-to-the-compiler,所以它比使用模板更快。这可能就是您的代码作者这样做的原因。