首页 > 解决方案 > StencilJS 的 Watch 装饰器不使用对象数组触发

问题描述

我想将一组对象作为道具传递给我的 StencilJS 组件。

import { Watch, Prop} from '@stencil/core';


@Component({
  tag: 'my-component',
  styleUrl: 'my-component.css',
  shadow: false
})
export class MyComponent {

  @Prop({ mutable: true }) events: Array<Object>;

  @Watch('events')
  eventsChanged(newValue: any, oldValue: any) {
    if (oldValue != newValue)
        this.events = newValue;
  }

  render() {
    return (
      // my HTML
    );
  }
}

我的应用程序上的 HTML:

<my-component ng-prop-events="$ctrl.events"></my-component>

我的events数组(在上述 HTML 的控制器中声明):

events: Array<Object> = [{
  label: 'Cool event =)',
  startDate: new Date('2021/02/14'),
  endDate: new Date('2021/02/14')
}];

每当用户单击复选框时,events都会收到一个新事件:

  this.events.push(event);

我可以看到event确实被推入events控制器中,但@WatchStencilJS 中的装饰器从未被触发。

该组件正在接收events变量,我可以在componentWillLoad().

为了Watch观察阵列中的变化,我必须做什么?

标签: javascriptangularjstypescriptstenciljs

解决方案


根据模具文档

对于数组,标准的可变数组操作,例如 push() 和 unshift() 不会触发组件更新。相反,应使用非可变数组运算符,因为它们返回新数组的副本。其中包括 map() 和 filter(),以及 ES6 扩展运算符语法。

例如,要将新项目推送到数组,请使用现有值和末尾的新值创建一个新数组:

@State() items: string[];

// our original array
this.items = ['ionic', 'stencil', 'webcomponents'];

// update the array
this.items = [
  ...this.items,
  'awesomeness'
]

推荐阅读