Vue基础-渲染函数-插槽

Vue基础-渲染函数-插槽

Vue 测试版本:Vue.js v2.5.13

先看个插槽的例子:

复制代码

{ {props.text}}

复制代码

复制代码

window.onload = function() {    
    Vue.component('child', {      
        template: `
      
`, }); new Vue({ el: '#app' }); };

复制代码

最终效果:

Vue基础-渲染函数-插槽_第1张图片

应该比较好理解,如果换成渲染函数,js 就是这样:
 

复制代码

window.onload = function() {
    Vue.component('child', {
        render(createElement){          
          let vnodes1 = this.$scopedSlots.default({
                  text: 'hello from child'
              });
          return createElement('div',[vnodes1]);
        }
    });

    new Vue({
        el: '#app'
    });
};

复制代码

前后比较对照下,结合文档,应该能看懂;

但是插槽有很多种形式,具名与否,作用域与否等等,综合在一起,做了个 demo,代码如下:

复制代码

    
default slot
header
footer from parent!
{ {props.text}}
{ {props.text}}

复制代码

如果依旧用 template ,js 就是这样:

复制代码

window.onload = function() {
    Vue.component('myele', {       
        template: `
        
vnodes0
{ {props.text}}
` }); Vue.component('child', { render(createElement) { let vnodes1 = this.$scopedSlots.default({ text: 'hello from child' }); return createElement('div', [vnodes1]); } }); new Vue({ el: '#app' }); };

复制代码

效果图:

Vue基础-渲染函数-插槽_第2张图片

如果用渲染函数实现,就是这样:

复制代码

window.onload = function() {
    Vue.component('myele', {
         render(createElement) {
             let vnodes0 = createElement('div', 'vnodes0'),
                 vnodes1 = this.$slots.default,
                 vnodes2 = this.$slots.header,
                 vnodes3 = this.$scopedSlots.footer({
                     text: 'footer child value'
                 }),
                 vnodes4 = createElement('child', {
                     scopedSlots: {
                         default: function(props) {
                             return createElement('span', props.text);
                         }
                     }
                 });
             return createElement('div', [vnodes0, vnodes1, vnodes2, vnodes3, vnodes4]);
         }
    });

    Vue.component('child', {
        render(createElement) {
            let vnodes1 = this.$scopedSlots.default({
                text: 'hello from child'
            });
            return createElement('div', [vnodes1]);
        }
    });

    new Vue({
        el: '#app'
    });
};

复制代码

两边一对照,结合文档,应该就比较清楚了

https://www.cnblogs.com/xianshenglu/p/8480151.html

你可能感兴趣的:(Vue基础-渲染函数-插槽)