How to create Ractive's subcomponents dynamically and change them programmatically

前端 未结 2 1197
借酒劲吻你
借酒劲吻你 2021-01-12 22:52

I can instantiate (sub)components manually using tags, but I don\'t know how to do it dynamically, or, how to insert and remove different components in the same area using t

2条回答
  •  长发绾君心
    2021-01-12 23:45

    Here's a dynamic component:

    Ractive.components.dynamic = Ractive.extend({
        template: '',
        components: {
            component: function() {
                return this.get('name');
            }
        },
        oninit: function(){
            this.observe('name', function(){
                this.reset();
            }, { init: false});
        }
    });
    

    Just pass in the name of the component it should implement:

    
    

    See it in action below

    Ractive.components.a = Ractive.extend({ template: 'I am A {{foo}}' });
    Ractive.components.b = Ractive.extend({ template: 'I am B {{foo}}' });
    Ractive.components.c = Ractive.extend({ template: 'I am C {{foo}}' });
    
    Ractive.components.dynamic = Ractive.extend({
        template: '',
        components: {
            component: function() {
                return this.get('name');
            }
        },
        oninit: function(){
            this.observe('name', function(){
                this.reset();
            }, { init: false});
        }
    });
    
    
    var r = new Ractive({
        el: document.body,
        template: '#template',
        data: {
            foo: 'foo',
            list: ['a', 'b', 'c'],
            name: 'a'
        }
    });
    
    

提交回复
热议问题