【发布时间】:2018-03-17 14:18:37
【问题描述】:
我是聚合物的新手,我一直在阅读文档并玩弄它,但我在理解 [[]] 单向数据流和{{}} 双向数据流。
谁能帮我理解其中的区别?
【问题讨论】:
标签: polymer polymer-2.x
我是聚合物的新手,我一直在阅读文档并玩弄它,但我在理解 [[]] 单向数据流和{{}} 双向数据流。
谁能帮我理解其中的区别?
【问题讨论】:
标签: polymer polymer-2.x
例如,将数据从一个元素向下传递给它的一个子元素被认为是单向数据绑定。如果此数据在子元素中被修改,则更改也会反映在父元素中。这是通过双向数据绑定实现的,因为它可以上下两个方向。
下面我添加了两个代码示例。
第一个示例说明了两个元素之间的one-away-data-binding。第二个示例显示 双向数据绑定,其中父元素反映了其子元素中发生的更改。
请注意,我使用的是 Polymer 1 的语法。但是,我相信 Polymer 2 中处理数据绑定的方式没有改变。
单向数据绑定
父元素
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../child-element/child-element.html">
<dom-module id="parent-element">
<template>
<style>
</style>
<div>
<h1>[[name]]</h1> <!-- This will print Pazzle -->
<!-- Use the imported child element and bind the name property-->
<child-element name="[[name]]"></child-element>
<!-- Will print Pazzle in a h2 element -->
</div>
</template>
<script>
Polymer({
is: 'parent-element',
properties: {
name: {
type: String,
value: 'Pazzle'
}
},
});
</script>
</dom-module>
父元素的子元素:
<link rel="import" href="../../bower_components/polymer/polymer.html">
<dom-module id="child-element">
<template>
<style>
</style>
<div>
<h2>[[name]]</h2> <!-- This will print Pazzle -->
</div>
</template>
<script>
Polymer({
is: 'child-element',
properties: {
name: {
type: String,
value: ''
}
},
});
</script>
</dom-module>
双向数据绑定
父元素
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../child-element/child-element.html">
<dom-module id="parent-element">
<template>
<style>
</style>
<div>
<!-- Use the imported child element and bind the name property-->
<child-element name="{{name}}"></child-element>
<!-- Will print Contis in a h2 element instead of Pazzle -->
</div>
</template>
<script>
Polymer({
is: 'parent-element',
properties: {
name: {
type: String,
value: ''
}
},
ready: function() {
this.name = "Pazzle";
}
});
</script>
</dom-module>
父元素的子元素:
<link rel="import" href="../../bower_components/polymer/polymer.html">
<dom-module id="child-element">
<template>
<style>
</style>
<div>
<h2>[[name]]</h2> <!-- This will print Contis -->
</div>
</template>
<script>
Polymer({
is: 'child-element',
properties: {
name: {
type: String,
value: '',
notify: true,
// notify will make it possible to send
// our changed Name property back up
observer: 'nameChanged'
}
},
nameChanged: function() {
if(this.name == 'Pazzle' || this.name == ''){
this.name = "Contis";
}
}
});
</script>
</dom-module>
【讨论】:
{{}}。那是那里链接的相关plunker。为什么不使用方括号[[]]?