vue slot 后备内容无法显示问题,并且还显示undefined问题

vue slot 后备内容无法显示问题

issus: https://github.com/vuejs/vue/issues/12153

原因 vue > 2.6.12 调整了slot组件的编译内容

示例代码

<template>
    <div>
        <slot>Hello World</slot>
    </div>
</template>

编译后模板是

vue-template-compiler = 2.6.12 编译结果

var HelloWorldvue_type_template_id_1f0af232_render = function () {
    var _vm = this;
    var _h = _vm.$createElement;
    var _c = _vm._self._c || _h;
    return _c('div', [_vm._t("default", [_vm._v(" HelloWorld ")])], 2)
}

vue-template-compiler = 2.6.14 编译结果

var HelloWorldvue_type_template_id_1f0af232_render = function () {
    var _vm = this;
    var _h = _vm.$createElement;
    var _c = _vm._self._c || _h;
    return _c('div', [_vm._t("default", function () {
        return [_vm._v(" HelloWorld ")]
    })], 2)
}

要注意 vue 与 vue-template-compiler 版本一致,主要原因是 vue 中 renderSlot 方法 调整,在 v2.6.13 版本,renderSlot 第二个参数支持 函数类型,同时 vue-template-compiler 编译slot 返回一个函数,但是v2.6.12 版本,renderSlot 第二个参数只是VNode,同时 vue-template-compiler 编译slot 直接返回一个VNode。因此如果 vue-template-compiler 版本比vue 版本高,就会出现这种情况。

注意如果是发布组件库,引用组件库的项目要和依赖库编译模板一致,如果项目使用vue-template-compiler@2.6.14,组件库依赖的vue-template-compiler@2.6.12,就会出现无法识别后备内容的情况

posted @ 2022-04-30 18:24  大圣巴巴  阅读(839)  评论(0编辑  收藏  举报