StencilJS 的 Watch 装饰器不触发对象数组

StencilJS's Watch decorator not firing with Array of Objects

我想将一个对象数组作为 prop 传递给我的 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的controller中声明):

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,但是 StencilJS 中的 @Watch 装饰器从未被触发。

组件正在接收 events 变量,我可以在 componentWillLoad() 中看到它。

为了让 Watch 观察到数组中的变化,我必须做什么?

根据the Stencil Docs

For arrays, the standard mutable array operations such as push() and unshift() won't trigger a component update. Instead, non-mutable array operators should be used as they return a copy of a new array. These include map() and filter(), and the ES6 spread operator syntax.

For example, to push a new item to an array, create a new array with the existing values and the new value at the end:

@State() items: string[];

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

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