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

總結

源碼體量不大,能夠總體閱讀下,瞭解並避免其餘文檔中沒有涉及的潛在的坑點。插件

相關文章
相關標籤/搜索