javascript - 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
控制器中,但@Watch
StencilJS 中的装饰器从未被触发。
该组件正在接收events
变量,我可以在componentWillLoad()
.
为了Watch
观察阵列中的变化,我必须做什么?
解决方案
根据模具文档:
对于数组,标准的可变数组操作,例如 push() 和 unshift() 不会触发组件更新。相反,应使用非可变数组运算符,因为它们返回新数组的副本。其中包括 map() 和 filter(),以及 ES6 扩展运算符语法。
例如,要将新项目推送到数组,请使用现有值和末尾的新值创建一个新数组:
@State() items: string[];
// our original array
this.items = ['ionic', 'stencil', 'webcomponents'];
// update the array
this.items = [
...this.items,
'awesomeness'
]
推荐阅读
- mysql - 从日期中提取年份并插入新字段
- python - 我们可以使用 Keras 进行视频数据增强吗?
- python - 通过 pandas 绘图界面绘制带有第二个 y 轴的 pandas 数据框时设置图例位置
- quasar-framework - Quasar Framework:在 QLayoutHeader/QToolbar 中隐藏 QToolbarTitle
- pimcore - Pimcore CSV 从文件夹位置上传并自动创建数据对象
- java - 如何按照提交的顺序通过 websocket 代理在 Spring Boot 中发送消息?
- sql-server - Kafka Connect with MSSQL 不适用于删除操作
- docker - Docker:如何将容器内的 IP 重定向到另一个 IP
- angular - 禁用角度中的默认键值管道排序
- google-apps-script - 具有两个 onEdit 实例的共享电子表格,删除错误的行