1. 程式人生 > >Vue學習筆記進階篇——Render函數

Vue學習筆記進階篇——Render函數

resp targe 無效 數據 iso 簡潔 如果 som cimage

本文為轉載,原文:Vue學習筆記進階篇——Render函數

基礎

Vue 推薦在絕大多數情況下使用 template 來創建你的 HTML。然而在一些場景中,你真的需要 JavaScript 的完全編程的能力,這就是 render 函數,它比 template 更接近編譯器。

<h1>
  <a name="hello-world" href="#hello-world">
    Hello world!
  </a>
</h1>

現在我們打算使用vue組件實現以上的渲染結果,我們渴望定義的接口如下:

<anchored-heading 
:level="1">Hello world!</anchored-heading>

level的值決定了,動態生成heading。
如果我們使用之前學到的知識實現通過level prop 動態生成heading 標簽的組件,你可能很快想到這樣實現:

<script type="text/x-template" id="anchored-heading-template">
  <h1 v-if="level === 1">
    <slot></slot>
  </h1>
  <h2 v-else-if="level === 2
"> <slot></slot> </h2> <h3 v-else-if="level === 3"> <slot></slot> </h3> <h4 v-else-if="level === 4"> <slot></slot> </h4> <h5 v-else-if="level === 5"> <slot></slot> </h5> <h6 v-else
-if="level === 6"> <slot></slot> </h6> </script>
Vue.component(‘anchored-heading‘, {
  template: ‘#anchored-heading-template‘,
  props: {
    level: {
      type: Number,
      required: true
    }
  }
})

在這種場景中使用 template 並不是最好的選擇:首先代碼冗長,為了在不同級別的標題中插入錨點元素,我們需要重復地使用 <slot></slot>
雖然模板在大多數組件中都非常好用,但是在這裏它就不是很簡潔的了。那麽,我們來嘗試使用render 函數重寫上面的例子:

<div id="app">
    <anchored-heading :level="1">hello</anchored-heading>
</div>
    Vue.component(‘anchored-heading‘,{
        render:function (createElement) {
            return createElement(
                ‘h‘ + this.level,
                this.$slots.default
            )
        },
        props:{
            level:{
                type:Number,
                required:true
            }
        }
    })

    new Vue({
        el:‘#app‘
    })

運行結果如下:

技術分享


簡單清晰很多!簡單來說,這樣代碼精簡很多,但是需要非常熟悉 Vue 的實例屬性。在這個例子中,你需要知道當你不使用 slot 屬性向組件中傳遞內容時,比如anchored-heading 中的 Hello world!, 這些子元素被存儲在組件實例中的 $slots.default中。

createElement參數

從上面的例子中,我們看到了使用了一個createElement的方法,這個方法的作用顯而易見,那就是用來創建元素,生成模板的。它接受的參數如下:

// @returns {VNode}
createElement(
  // {String | Object | Function}
  // 一個 HTML 標簽字符串,組件選項對象,或者一個返回值類型為String/Object的函數,必要參數
  ‘div‘,
  // {Object}
  // 一個包含模板相關屬性的數據對象
  // 這樣,您可以在 template 中使用這些屬性.可選參數.
  {
    // (詳情見下一節)
  },
  // {String | Array}
  // 子節點 (VNodes),由 `createElement()` 構建而成,
  // 或簡單的使用字符串來生成“文本結點”。可選參數。
  [
    ‘先寫一些文字‘,
    createElement(‘h1‘, ‘一則頭條‘),
    createElement(MyComponent, {
      props: {
        someProp: ‘foobar‘
      }
    })
  ]
)
  1. 第一個參數是一個html標簽,前面已經說了這個函數是用來創建元素,但是創建什麽元素呢,那就取決於第一個參數,而這個參數就是所需創建元素的html標簽,如div, span, p等.
  2. 第二個參數是可選參數,這個參數是用來描述所創建的元素的,為所創建的元素設置屬性,如class, style, props等等.
  3. 第三個參數就是創建的元素的子節點了。由 createElement() 構建而成,
    或簡單的使用字符串來生成“文本結點”。也同樣是可選參數。

深入data object參數

有一件事要註意:正如在模板語法中,v-bind:classv-bind:style ,會被特別對待一樣,在 VNode 數據對象中,下列屬性名是級別最高的字段。該對象也允許你綁定普通的 HTML 特性,就像 DOM 屬性一樣,比如 innerHTML (這會取代 v-html指令)。

{
  // 和`v-bind:class`一樣的 API
  ‘class‘: {
    foo: true,
    bar: false
  },
  // 和`v-bind:style`一樣的 API
  style: {
    color: ‘red‘,
    fontSize: ‘14px‘
  },
  // 正常的 HTML 特性
  attrs: {
    id: ‘foo‘
  },
  // 組件 props
  props: {
    myProp: ‘bar‘
  },
  // DOM 屬性
  domProps: {
    innerHTML: ‘baz‘
  },
  // 事件監聽器基於 `on`
  // 所以不再支持如 `v-on:keyup.enter` 修飾器
  // 需要手動匹配 keyCode。
  on: {
    click: this.clickHandler
  },
  // 僅對於組件,用於監聽原生事件,而不是組件內部使用 `vm.$emit` 觸發的事件。
  nativeOn: {
    click: this.nativeClickHandler
  },
  // 自定義指令. 註意事項:不能對綁定的舊值設值
  // Vue 會為您持續追蹤
  directives: [
    {
      name: ‘my-custom-directive‘,
      value: ‘2‘,
      expression: ‘1 + 1‘,
      arg: ‘foo‘,
      modifiers: {
        bar: true
      }
    }
  ],
  // Scoped slots in the form of
  // { name: props => VNode | Array<VNode> }
  scopedSlots: {
    default: props => createElement(‘span‘, props.text)
  },
  // 如果組件是其他組件的子組件,需為 slot 指定名稱
  slot: ‘name-of-slot‘,
  // 其他特殊頂層屬性
  key: ‘myKey‘,
  ref: ‘myRef‘
}

完整示例

有了以上的知識,我們就可以實現我們想要實現的功能了,以下為完整示例:

<div id="app">
    <my-heading :level="2">
        <p>Hello Chain</p>
    </my-heading>
</div>
var getChildrenTextContent = function (children) {
        return children.map(function (node) {
            return node.children ? getChildrenTextContent(node.children)
                :node.text
        }).join(‘‘)
    }
    Vue.component(‘my-heading‘, {
        render:function (createElement) {
            var headingId = getChildrenTextContent(this.$slots.default)
                .toLowerCase()
                .replace(/\W/g, ‘-‘)
                .replace(/(^\-|\-$)/g, ‘‘)
            return createElement(
                ‘h‘ + this.level,
                [
                    createElement(‘a‘,{
                        attrs:{
                            name:headingId,
                            href:‘#‘+headingId
                        }
                    }, this.$slots.default)
                ]
            )
        },
        props:{
            level:{
                type:Number,
                required:true
            }
        }
    })

    new Vue({
        el:‘#app‘
    })

運行結果:

技術分享

約束

VNodes 必須唯一

組件樹中的所有 VNodes必須是唯一的。這意味著,下面的 render function 是無效的:

render: function (createElement) {
  var myParagraphVNode = createElement(‘p‘, ‘hi‘)
  return createElement(‘div‘, [
    // 錯誤-重復的VNodes
    myParagraphVNode, myParagraphVNode
  ])
}

如果你真的需要重復很多次的元素/組件,你可以使用工廠函數來實現。例如,下面這個例子 render 函數完美有效地渲染了 20 個重復的段落:

render: function (createElement) {
  return createElement(‘div‘,
    Array.apply(null, { length: 20 }).map(function () {
      return createElement(‘p‘, ‘hi‘)
    })
  )
}

使用javascript代替模板功能

v-ifv-for

由於使用原生的 JavaScript 來實現某些東西很簡單,Vue 的 render 函數沒有提供專用的 API。比如, template 中的v-ifv-for,這些都會在 render 函數中被 JavaScript 的 if/elsemap重寫。 請看下面的示例:

<div id="app-list">
    <list-component :items="items"></list-component>
</div>
    Vue.component(‘list-component‘,{
        render:function (createElement) {
            if (this.items.length){
                return createElement(‘ul‘,this.items.map(function (item) {
                    return createElement(‘li‘, item.name)
                }))
            }
            else {
                return createElement(‘p‘, ‘No items found. ‘)
            }
        },
        props:[‘items‘]
    })

    new Vue({
        el:‘#app-list‘,
        data:{
            items:[
                {name:‘item1‘},
                {name:‘item1‘},
                {name:‘item1‘}
            ]
        }
    })

運行結果:

技術分享


當items為空時:

技術分享

v-model

render函數中沒有與v-model相應的api - 你必須自己來實現相應的邏輯。請看下面一個實現了雙向綁定的render示例:

<div id="app-input">
    <p>{{value}}</p>
    <my-input :value="value" @input="updateValue"></my-input>
</div>
    Vue.component(‘my-input‘,{
        render:function (createElement) {
            var self = this
            return createElement(‘input‘,{
                domProps:{
                    value:self.myValue
                },
                on:{
                    input:function (event) {
                        self.myValue = event.target.value
                        self.$emit(‘input‘, event.target.value)
                    }
                },
                attrs:{
                    type:‘text‘,
                    step:10
                }
            })
        },
        props:[‘value‘],
        computed:{
            myValue:function () {
                return this.value
            }
        },
    })

    var app_input = new Vue({
        el:‘#app-input‘,
        data:{
            value:‘‘
        },
        methods:{
            updateValue:function (val) {
                this.value = val
            }
        }
    })

運行結果:

技術分享


這就是深入底層要付出的,盡管麻煩了一些,但相對於 v-model來說,你可以更靈活地控制。

事件和按鍵修飾符

對於 .passive.capture.once事件修飾符, Vue 提供了相應的前綴可以用於 on:

Modifier(s)Prefix
.passive &
.capture !
.once ~
.capture.once or .once.capture ~!

例如:

on: {
  ‘!click‘: this.doThisInCapturingMode,
  ‘~keyup‘: this.doThisOnce,
  `~!mouseover`: this.doThisOnceInCapturingMode
}

對於其他的修飾符, 前綴不是很重要, 因為你可以直接在事件處理函數中使用事件方法:

Modifier(s)Equivalent in Handler
.stop event.stopPropagation()
.prevent event.preventDefault()
.self if (event.target !== event.currentTarget) return
Keys:.enter, .13 if (event.keyCode !== 13) return (change 13 to another key code for other key modifiers)
Modifiers Keys:.ctrl, .alt, .shift, .meta if (!event.ctrlKey) return (change ctrlKey to altKey, shiftKey, or metaKey, respectively)

我們在上一個例子上加入一個keyup的事件,當按了enter按鍵時彈框。修改createElement的第二參數的on, 修改後的代碼如下:

on:{
    input:function (event) {
       self.myValue = event.target.value
       self.$emit(‘input‘, event.target.value)
    },
    ‘keyup‘:function (event) {
        if (event.keyCode == 13){
            alert(event.target.value)
        }
    }
}

在輸入框內輸入內容,按回車鍵,結果如下:

技術分享

slots

你可以從this.$slots獲取VNodes列表中的靜態內容:

render: function (createElement) {
  // `<div><slot></slot></div>`
  return createElement(‘div‘, this.$slots.default)
}

還可以從this.$scopedSlots 中獲得能用作函數的作用域插槽,這個函數返回 VNodes:

render: function (createElement) {
  // `<div><slot :text="msg"></slot></div>`
  return createElement(‘div‘, [
    this.$scopedSlots.default({
      text: this.msg
    })
  ])
}

請看下面使用this.$scopedSlots的例子:

<div id="app-slot">
    <com-scoped-slot>
        <template scope="props">
            <p>parent value</p>
            <p>{{props.text}}</p>
        </template>
    </com-scoped-slot>
</div>
    Vue.component(‘com-scoped-slot‘,{
        render:function (h) {
            return h(‘div‘, [
                this.$scopedSlots.default({
                    text:this.msg
                })
            ])
        },
        props:[‘text‘],
        data:function () {
            return {
                msg:‘child value‘
            }
        }
    })

    new Vue({
        el:‘#app-slot‘
    })

運行結果:

技術分享

上一節:Vue學習筆記進階篇——過渡狀態
返回目錄

Vue學習筆記進階篇——Render函數