Vue基礎-渲染函數-父子組件-傳遞數據

Vue 測試版本:Vue.js v2.5.13html

作了個 demo,把父子組件的數據都綁定到 Vue 實例 app 上,註釋中的 template 相對好理解些vue

<div id="app">
        <myele :level="level">
        </myele>
        <child :level="level">
            <p>para default</p>
            <span slot="span">a span</span>
            <div slot="div">a div</div>
            <div slot="footer" slot-scope="props">{{props.text}}</div>
        </child>
    </div>
window.onload = function() { Vue.component('myele', { render(createElement) { return createElement('child', { props: { level: this.level }, scopedSlots: { footer: function(props) { return createElement('div', [createElement('span', props.text)]); } } }, [createElement('span', 'hello'), 'world']); }, /* template:` <child :level="level"> <span>hello</span>world <div slot="footer" slot-scope="props"> <span>{{props.text}}</span> </div> </child> `,*/ props: ['level'] }); Vue.component('child', { render(createElement) { let nodes0 = this.$slots.default; let nodes1 = this.$slots.span; let nodes2 = this.$slots.div; let nodes3 = this.$scopedSlots.footer({ text: 'scopedSlots-foooter' }); return createElement('h' + this.level, [nodes0, nodes1, nodes2, nodes3]); }, props: ['level'] }); new Vue({ el: '#app', data: { level: 1 } }); };

效果以下:node

image

其實最初不是這樣寫的,js 是這樣:app

window.onload = function() { Vue.component('myele', { render(createElement) { //複雜的做用域插槽單獨拎出來;
            let scopedSlotsNode = createElement('div', { scopedSlots: { footer: function(props) { return createElement('span', props.text); } } }); return createElement('child', { props: { level: this.level } }, [createElement('span', 'hello'), 'world', scopedSlotsNode]); }, /* template:` <child :level="level"> <span>hello</span>world <div> <span slot="footer" slot-scope="props"> {{props.text}} </span> </div> </child> `,*/ props: ['level'] }); Vue.component('child', { render(createElement) { let nodes0 = this.$slots.default; let nodes1 = this.$slots.span; let nodes2 = this.$slots.div; let nodes3 = this.$scopedSlots.footer({ text: 'scopedSlots-foooter' }); return createElement('h' + this.level, [nodes0, nodes1, nodes2, nodes3]); }, props: ['level'] }); new Vue({ el: '#app', data: { level: 1 } }); };

結果報錯,ide

image

半天沒反應過來,後來想一想,明白了,解釋就在 template 裏,不明白的話,再看看;測試

參考文檔:ui

https://cn.vuejs.org/v2/guide/render-function.html#插槽this

相關文章
相關標籤/搜索