Vue 源码阅读(八) JSX

介绍

Vue 推荐在绝大多数状况下使用模板来建立你的 HTML。然而在一些场景中,你真的须要 JavaScript 的彻底编程的能力。这时你能够用渲染函数,它比模板更接近编译器。

渲染函数在某些场景下,编写时没有模板直观、简单。vue

这就是为何会有一个 Babel 插件,用于在 Vue 中使用 JSX 语法,它能够让咱们回到更接近于模板的语法上。

原由

在官方给的使用文档中,只是简单的介绍了一些基础用法,使用过程当中遇到以下问题:git

ElementUI 中 Form 组件有一个叫作 model 的 props,一般会这么写 JSX :github

{
    render() {
        <el-form model={{ }}>
            ...
        </el-form>
    }
}

经过 Vue DevTools,能够查看到 Form 组件绑定的 model 值为 undefined编程

分析

查看源码时,能够发现 model 是 root attributes,被当作 attributes 而不是 propsbabel

const rootAttributes = ['staticClass', 'class', 'style', 'key', 'ref', 'refInFor', 'slot', 'scopedSlots', 'model']

// ...

if (rootAttributes.includes(name)) {
    attributes[name] = value
} else {
    
}

解决方案

设计组件 props 时,应该避免使用 rootAttributes 包含的值。若是已经那么设计,能够这样处理:函数

{
    render() {
        <el-form props={{ model: { } }}>
            ...
        </el-form>
    }
}

总结

源码体量不大,能够总体阅读下,了解并避免其余文档中没有涉及的潜在的坑点。插件

相关文章
相关标签/搜索