如何动态创建Ractive的子组件并以编程方式更改它们

Pau*_*ica 6 components ractivejs

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

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

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

但是新的(子)组件无法在胡子中看到它的父实例的数据,只能看到他自己的数据.

mar*_*pdx 10

这是一个动态组件:

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

只需传入它应该实现的组件的名称:

<dynamic name='{{name}}'/>
Run Code Online (Sandbox Code Playgroud)

请参阅下面的操作

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'
    }
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • @LiorCohen我认为很久以前就有一个ractive bug需要这样做.它似乎不再需要了! (2认同)