我可以使用标签手动实例化(子)组件,但是我不知道如何动态地执行它,或者不知道如何使用标签在同一区域插入和删除不同的组件。

今天,我以这种方式实例化每个(子)组件:

Ractive.load( '/templates/global/example.html' ).then( function ( Example )
{
       ractive.components.example = new Example( { el : 'aside' } );
});

但是新的(子)组件在 mustache 中看不到其父实例的数据,只能看到他自己的数据。

最佳答案

这是一个动态组件:

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

只需传递它应该实现的组件的名称即可:
<dynamic name='{{name}}'/>

看到下面的行动

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: '<component/>',
    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'
    }
});
<script src="http://cdn.ractivejs.org/latest/ractive.js"></script>
<script id='template' type='text/ractive'>

    {{#each list}}
    <input type='radio' name='{{name}}' value='{{.}}'>{{.}}
    {{/each}}
    <br>
    <dynamic name='{{name}}'/>

</script>

关于components - 如何动态创建Ractive的子组件并以编程方式更改它们,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31075341/

10-12 13:03