Polymer 2条件属性实现方法咨询:仅找到Polymer 1相关资料
Hey there! I totally get the frustration when old Polymer 1 docs clog up search results—let me walk you through exactly how to handle conditional attributes in Polymer 2, with practical examples you can drop right into your code.
1. Boolean Attribute Conditional Binding
Polymer 2 has a dedicated syntax for boolean attributes (like disabled, checked, or hidden) that automatically adds/removes the attribute based on a boolean property. Use the ?= prefix in your template:
<dom-module id="my-custom-button"> <template> <!-- Button will have the `disabled` attribute only when isDisabled is true --> <button ?disabled="[[isDisabled]]">Submit</button> <!-- Checkbox gets `checked` attribute when isChecked is true --> <input type="checkbox" ?checked="[[isChecked]]"> </template> <script> Polymer({ is: 'my-custom-button', properties: { isDisabled: { type: Boolean, value: false // Default state: enabled }, isChecked: { type: Boolean, value: true } } }); </script> </dom-module>
2. Regular Attribute Conditional Binding (Dynamic Values)
For non-boolean attributes (like src, class, or href), use a computed property to return the appropriate value based on your conditions. Use the $= prefix to bind the computed result to the attribute:
Example: Dynamic Image Source
<dom-module id="responsive-image"> <template> <img src$="[[_getImageSrc(screenSize)]]" alt="Responsive image"> </template> <script> Polymer({ is: 'responsive-image', properties: { screenSize: { type: String, value: 'mobile' } }, _getImageSrc(size) { // Return different paths based on the screenSize property switch(size) { case 'desktop': return '/assets/images/desktop-header.jpg'; case 'tablet': return '/assets/images/tablet-header.jpg'; default: return '/assets/images/mobile-header.jpg'; } } }); </script> </dom-module>
Example: Conditional CSS Classes
You can even combine multiple conditions to build dynamic class lists:
// Inside your element's script _computeCardClasses(isActive, isFeatured) { let classes = 'card'; if (isActive) classes += ' card--active'; if (isFeatured) classes += ' card--featured'; return classes; }
Then bind it in the template:
<div class$="[[_computeCardClasses(isActive, isFeatured)]]"></div>
Key Difference from Polymer 1
Unlike Polymer 1, which allowed inline {{if}} logic directly in templates, Polymer 2 aligns closer to native Web Components standards—relying on property bindings and computed properties for conditional logic. This makes your code more maintainable and compatible with modern web standards.
If you’re dealing with more complex conditional rendering (not just attributes), you can also use the <dom-if> template to toggle entire elements, but for attribute-specific conditions, the methods above are the most efficient.
内容的提问来源于stack exchange,提问作者AlexBenoit

