我想把一个对象数组作为道具传递给我的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
,但StencilJS中的@Watch
装饰器从未被触发。
组件正在接收events
变量,我可以在componentWillLoad()
中看到它。
我要做什么,以使Watch
观察到我的数组的变化?
根据Stencil Docs:
对于数组,标准的可变数组操作,如push()和unshift()不会触发组件更新。相反,应该使用非可变数组操作符,因为它们返回新数组的副本。其中包括map()和filter(),以及ES6扩展操作符语法。
例如,要将一个新项压入数组,用现有值创建一个新数组,并将新值放在数组的末尾:
@State() items: string[];
// our original array
this.items = ['ionic', 'stencil', 'webcomponents'];
// update the array
this.items = [
...this.items,
'awesomeness'
]