attribute 和 property
总结:DOM property、DOM attribute区别导致自定义标签在 Vue、React 中应用时体现不一,外围思路是做好映射关系。
React中应用 WCs 标签:
const App = () => <my-cell desc='false'>Cell</my-cell>export default App;
不会走到WCs的 set
,因为传递的是 property
。且以上传递的是一个字符串。
class MyCell extends HTMLElement { ... get desc() { return this.getAttribute('desc'); }+ set desc(value) {+ // 不会走到这里+ this.setAttribute('desc', value);+ } ...}
Vue中应用 WCs 标签:
<template> <my-cell desc="false">Cell</my-cell></template>
会走到 set
,Vue 中 desc
示意传递的是 attribute
。
class MyCell extends HTMLElement { ... get desc() { return this.getAttribute('desc'); }+ set desc(value) {+ // 与React不同,Vue我的项目中应用会走到这里+ this.setAttribute('desc', value);+ } ...}
如何解决?
为了兼容 WCs 在 React 和 Vue 我的项目中应用一致性,须要在 WCs 外部去绑定this
属性
connectedCallback() {+ this.desc = this.desc; // attribute -> property 映射}
布尔值属性传递
自定义一个标签 <my-cell />
Vue
<my-cell desc="false">Cell</my-cell>
下面属性传的是类型是 string
字符串
如果这样传:<my-cell :desc="false">Cell</my-cell>
下面属性传递的类型是 boolean
布尔值