vue 渲染函數(shù) & JSX

渲染函數(shù) render

通過渲染函數(shù)渲染組件

Vue.component('myComponent', {
  render (h) { // createElement
    return h(
      'div', // HTML tag、自定義組件、異步組件
      { // 屬性對象
        attrs: { // 標(biāo)簽屬性
          id: 'wrap'
        },
        class: { // 類名
          'my-com': true
        },
        props: { // DOM 屬性,props
          user: 'wdapp'
        },
        style: { // 樣式
          color: 'red',
          fontSize: '18px'
        },
        on: { // 綁定事件
          mouseenter: function () {
            console.log('click')
          }
        },
        key: 'myKey', // 唯一key值
        ref: 'myRef', // 獲取DOM元素的標(biāo)識
      },
      [// 子節(jié)點
        "文本節(jié)點", //  文本節(jié)點
        h('h1', "內(nèi)容"), // 虛擬節(jié)點
      ]
    )
  }
})

渲染后:

// html
<div id="wrap" class="my-com" style="color: red; font-size: 18px;">文本節(jié)點<h1>內(nèi)容</h1></div>

JSX

通過以上方式創(chuàng)建虛擬DOM,語法比較繁瑣。可以使用JSX(JavaScript XML)語法,配合createElement輕松的創(chuàng)建虛擬DOM。

Vue使用JSX語法,需要配合Babel插件進(jìn)行解析。

import AnchoredHeading from './AnchoredHeading.vue'

new Vue({
  el: '#demo',
  render: function (h) {
    return (
      <AnchoredHeading level={1}>
        <span>Hello</span> world!
      </AnchoredHeading>
    )
  }
})

函數(shù)式組件

Vue.component('smart-list', {
  functional: true, // 函數(shù)式組件
  props: { // 屬性
    items: {
      type: Array,
      required: true
    }
  },
  // context 上下文
  render: function (createElement, context) {
    return createElement(
      "button",
      context.data, // 把smart-list自定義組件的整個"數(shù)據(jù)對象"傳遞給button
      context.children // 把smart-list自定義組件的所有子節(jié)點傳遞給button
    )
  }
})

"數(shù)據(jù)對象": 指的是上文提到的createElement的第二個參數(shù),之類包括 props、class、id等

使用組件:

<smart-list id="Smart" class="smart-list" @click="handelClick">Smart Btn</smart-list>

渲染為:

<button id="Smart" class="smart-list">Smart Btn</button>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容