public setAttribute()

in packages/miniapp-runtime/src/dom/element.ts [132:219]


  public setAttribute(qualifiedName: string, value: any): void {
    process.env.NODE_ENV !== 'production' && warn(
      isString(value) && value.length > PROPERTY_THRESHOLD,
      `元素 ${this.nodeName} 的 ${qualifiedName} 属性值数据量过大,可能会影响渲染性能。考虑在 CSS 中使用 base64。`,
    );

    const isPureView = this.nodeName === VIEW && !isHasExtractProp(this) && !this.isAnyEventBinded();

    if (qualifiedName !== STYLE) {
      MutationObserver.record({
        target: this,
        type: MutationRecordType.ATTRIBUTES,
        attributeName: qualifiedName,
        oldValue: this.getAttribute(qualifiedName),
      });
    }

    switch (qualifiedName) {
      case STYLE:
        this.style.cssText = value as string;
        break;
      case ID:
        if (this.uid !== this.sid) {
          // eventSource[sid] 永远保留,直到组件卸载
          // eventSource[uid] 可变
          eventSource.delete(this.uid);
        }
        value = String(value);
        this.props[qualifiedName] = this.uid = value;
        eventSource.set(value, this);
        break;
      default:
        this.props[qualifiedName] = value as string;

        if (qualifiedName.startsWith('data-')) {
          if (this.dataset === EMPTY_OBJ) {
            this.dataset = Object.create(null);
          }
          this.dataset[toCamelCase(qualifiedName.replace(/^data-/, ''))] = value;
        }
        break;
    }

    // Serialization
    if (!this._root) return;

    const componentsAlias = getComponentsAlias();
    const _alias = componentsAlias[this.nodeName];
    const viewAlias = componentsAlias[VIEW]._num;
    const staticViewAlias = componentsAlias[STATIC_VIEW]._num;
    const catchViewAlias = componentsAlias[CATCH_VIEW]._num;
    const { _path } = this;

    qualifiedName = shortcutAttr(qualifiedName);

    const payload = {
      path: `${_path}.${toCamelCase(qualifiedName)}`,
      value: isFunction(value) ? () => value : value,
    };

    hooks.call('modifySetAttrPayload', this, qualifiedName, payload, componentsAlias);

    if (_alias) {
      const qualifiedNameAlias = _alias[qualifiedName] || qualifiedName;
      payload.path = `${_path}.${toCamelCase(qualifiedNameAlias)}`;
    }

    this.enqueueUpdate(payload);

    if (this.nodeName === VIEW) {
      if (toCamelCase(qualifiedName) === CATCHMOVE) {
        // catchMove = true: catch-view
        // catchMove = false: view or static-view
        this.enqueueUpdate({
          path: `${_path}.${Shortcuts.NodeName}`,
          value: value ? catchViewAlias : (
            this.isAnyEventBinded() ? viewAlias : staticViewAlias
          ),
        });
      } else if (isPureView && isHasExtractProp(this)) {
        // pure-view => static-view
        this.enqueueUpdate({
          path: `${_path}.${Shortcuts.NodeName}`,
          value: staticViewAlias,
        });
      }
    }
  }