vue-render函數(shù)

Vue 推薦在絕大多數(shù)情況下使用 template 來(lái)創(chuàng)建你的 HTML。然而在一些場(chǎng)景中,你真的需要 JavaScript 的完全編程的能力,這就是 render 函數(shù),它比 template 更接近編譯器。vue提供了render函數(shù)大大的提高了JavaScript的編程能力,雖然在日常的使用中是比較少見(jiàn)的但是理解render函數(shù)對(duì)應(yīng)加深對(duì)Vue組件的使用都是很有幫助的。下面我們就針對(duì)render函數(shù)進(jìn)行探討。


render函數(shù)提供一個(gè)createElement,而createElement可接受三個(gè)參數(shù)具體情況如下:

第一個(gè)參數(shù)

第一個(gè)參數(shù)可以是HTML標(biāo)簽名,組件或者函數(shù)都可以。

{
   type: String || Object || Function,
   required: true
}

??

<template>
  <div class="dome">
    <div id="app">
    </div>
  </div>
</template>

<script>
  Vue.components('dom', {
    render: function (createElement) {
      return createElement('div');
    }
  });
  new Vue({
    el: '#app'
  });</script>

第二個(gè)參數(shù)

第二個(gè)參數(shù)為創(chuàng)建元素的一些屬性。

{
  type: Object,
  required: false
}

??

Vue.components('dom', {
    render: function (createElement) {
      return createElement('div', {
        'class': {
          container: true
        },
        style: {
          cursor: 'pointer'
        },
        domProps: {
          innHTML: 'baz'
        }
      });
    }
  });
  new Vue({
    el: '#app'
  });

第三個(gè)參數(shù)

第三個(gè)參數(shù)為創(chuàng)建元素的子節(jié)點(diǎn)。

{
  type: String || Array,
  required: false
}

??

<script>
  Vue.components('dom', {
    render: function (createElement) {
      return createElement('div', [
        createElement('h1', '主標(biāo)'),
        createElement('h2', '副標(biāo)')
      ]);
    }
  });
  new Vue({
    el: '#app'
  });
</script>

上述就是render幾個(gè)參數(shù)的具體信息,而用render函數(shù)生成的組件的子元素就在$slots.default中。

Vue提供的實(shí)例方法在render函數(shù)中使用

<template>
  <div class="dome">
    <div id="app">
      <dom-input
        :value="pValue"
        @input="val=>pValue=val">
      </dom-input>
    </div>
  </div>
</template>

<script>
  Vue.components('dom-input', {
    render: function (createElement) {
      const _this = this;
      return createElement('div', {
        domPopps: {
          value: _this.name
        },
        on: {
          input: function () {
            _this.$emit('input', event.taget.value);
          }
        }
      });
    },
    props: {
      value: String
    }
  });
  new Vue({
    el: '#app',
    data: {
      pValue: ''
    }
  });
</script>

上面的例子中我們創(chuàng)建了一個(gè)input組件,在組件中當(dāng)輸入的觸發(fā)了input事件emit了input的value;而在外層中接受了這個(gè)value讓pValue的值等于value。而pValue又通過(guò)props把值傳入input組件中從而實(shí)現(xiàn)了類似v-model的數(shù)據(jù)綁定。

通過(guò)了上面render函數(shù)的一個(gè)例子我們看到了props和事件的觸發(fā)的使用。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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