写在前面
虽然所有 HTML 属性都是字符串,但由于 HTML 是纯文本格式,当你在书写自定义组件的时候可能会经常遇到布尔属性(boolean attributes),那么如何正确使用布尔属性呢?本文来讲解一二。
篇幅较小,没有使用/书写过 Web Components 的同学可以跳过本文,想要了解的可以参考前面写过的文章: 哈啰前端Web Components最佳实践
相关的文章还有: 关于自定义组件属性在 Vue 和 React 中不同表现的探讨
声明 Boolean attributes
自定义元素上不存在布尔属性——当人们谈论它们时,他们指的是一个简单的约定:如果一个属性存在于一个元素上,那么它是真的,而如果一个属性不存在于一个元素上,那么它就是错误的:
<!-- a boolean attribute, open, set to true-->
<my-component open></my-component>
<!-- a boolean attribute, open, set to false-->
<my-component></my-component>
设置 Boolean attributes
1、如果需要设置属性为 true:
const el = document.querySelector('my-component');
el.setAttribute('open', '');
/*
setting an empty string will set the
attribute with no value on the element
*/
2、如果需要设置属性为 false:
el.removeAttribute('open');
3、读取布尔属性:
const isOpen = el.hasAttribute('open');
需要注意的几个点
-
可以看到,当使用
hasAttribute时,不需要将属性设置为空字符串,将属性设置为任何值都将返回 true,但按照惯例,布尔属性应该使用空字符串。 -
同样重要的是要认识到字符串
true和false对于 HTML 属性没有专门的含义,将布尔属性设置为true或false将使布尔属性为true。 -
没有明确的方法将布尔属性设置为
false,必须将其删除。getAttribute为不存在的属性返回 null,但不能setAttribute('open', null),这将导致open="null"被视为true。
以上是本次分享的所有内容,希望对大家有帮助,谢谢~