我正在尝试找出实现这一目标的最佳方法是什么。我可能以错误的方式思考它,但这就是我“想要”实现的目标:
<div>
{{#if selection}}
<div>There is a selection in Component!</div>
{{/if}}
<Component />
</div>
其中selection
是Component
中的一个计算属性,我想在外部作用域中使用它。有什么方法可以引用组件实例的属性吗?
例如:
<div>
{{#if foo.selection}}
<div>There is a selection in Component!</div>
{{/if}}
<Component id="foo" />
</div>
或者这是错误的思考方式吗?我能想到的唯一其他方法是使用事件。
<div>
{{#if selection}}
<div>There is a selection in Component!</div>
{{/if}}
<Component on-selection="select" />
</div>
但这并不优雅,因为它需要额外的代码:
ractive.on("selection", function(e) { this.set("selection", ...); });
最佳答案
从版本 0.8
开始,您可以直接将事件映射到数据值(请参阅 http://jsfiddle.net/0zubyyov/ ),这很好地将组件内部与父组件解耦:
模板:
<script id='template' type='text/ractive'>
{{#if selected}}selected!{{/if}}
<component on-select='set("selected", $1)'/>
</script>
<script id='component' type='text/ractive'>
<input type='checkbox' on-change='fire("select", event.node.checked)'>
</script>
JavaScript:
Ractive.components.component = Ractive.extend({
template: '#component',
data: { selected: false }
});
var r = new Ractive({
el: document.body,
template: '#template'
});
使用 0.7
您可能会考虑向保持最新的组件传递一个值(请参阅 http://jsfiddle.net/gr6d7vs8/ )。我在这一篇中更明确地谈到了处理计算属性:
<script id='template' type='text/ractive'>
{{#if selected}} selected! {{/if}}
<component selected='{{selected}}'/>
</script>
<script id='component' type='text/ractive'>
<input type='checkbox' checked='{{checked}}'>
</script>
JavaScript:
Ractive.components.component = Ractive.extend({
template: '#component',
data: { checked: false, allowed: true },
computed: {
isChecked () {
return this.get('checked') && this.get('allowed')
}
},
oninit(){
this.observe('isChecked', isChecked => {
this.set('selected', isChecked);
});
}
});
关于javascript - 读取 Ractive.js 中的计算属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33638023/