vuejs2 - 基于 Vue2 类的数据属性不是反应式的
问题描述
我在基于 vue2 类的组件中使用打字稿。使用自定义类型 KeyValuePair 时,sampleData 属性在组件中不响应。
export type KeyValuePair<T> = {
[key in string | number]: T;
};
<template>
<div>
<!-- remains empty even after sampleData is updated ! -->
{{ sampleData }}
</div>
<template>
<script>
@Component()
export default class Sample extends Vue {
sampleData: KeyValuePair<string> = {};
//assume it gets called somehow
sampleMethod() {
this.sampleData['0'] = 'sample data';
}
}
</script>
还尝试从 getter 访问 sampleData 道具,但仍然无法正常工作。任何解决方案或建议可能会有所帮助!
解决方案
VueJS 无法检测对象中的属性添加或删除。而且由于0
运行时示例数据中不存在密钥,因此稍后添加它不会产生您期望的结果。
您将需要使用Vue.set
来实现您想要的:
sampleMethod() {
Vue.set(this.sampleData, '0', 'sample data');
}
}
推荐阅读
- c++ - 在 tinkercad 中使用伺服库导致奇怪的行为
- html - 为什么使用 justify-content: center 时我的按钮不居中
- cron - 如何使用非标准 schedule_interval 控制计划 DAG 的首次运行
- python - 如何使用 exchangelib 连接到使用 Outlook Web App (OWA) 的工作电子邮件?
- python - 使用 scikit-neuralnetwork 时 scikit-learn 出错
- javascript - 测试 Lambda 函数时 index.handler 未定义或未导出
- python - 在 jinja-flask 框架中发布 json 数据
- jquery - 未选择选项并且不会清除错误时,Jquery 验证进行验证
- typescript - 将 pg-promise 任务与 graphql 和 dataloader 一起使用
- python - 如何根据用户组为字段设置odoo域过滤器?