关于web-components:Web-Components-中属性在Vue和React中的不同表现

29次阅读

共计 864 个字符,预计需要花费 3 分钟才能阅读完成。

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 布尔值

React

正文完
 0