在emberjs模板中观察json对象的变化

2exbekwf  于 2023-11-18  发布在  其他
关注(0)|答案(1)|浏览(245)

如何观察json对象在updateJson模板中的变化,这是我的测试代码,我希望在单击updateJson后显示jsonChange按钮,但它没有
test.hbs

  1. <button {{on "click" this.updateJson}} >updateJson</button>
  2. {{#if this.testJsonChanges}}
  3. <button>jsonChange</button>
  4. {{/if}}

字符串
test.js

  1. export default class TestController extends Controller {
  2. @tracked testjson = {key1:'value1', key2:'value2'};
  3. @action updateJson() {
  4. this.testjson.key1 = 'valuex';
  5. }
  6. get testJsonChanges() {
  7. return this.testjson.key1 != 'value1';
  8. }
  9. }

sf6xfgos

sf6xfgos1#

@tracked仅适用于引用,就像const仅在引用上是常量一样--如果您希望跟踪属性的更改,则需要使用TrackedObject

  1. import { TrackedObject } from 'tracked-built-ins';
  2. export default class TestController extends Controller {
  3. testjson = new TrackedObject({key1:'value1', key2:'value2'});
  4. @action updateJson() {
  5. this.testjson.key1 = 'valuex';
  6. }
  7. get testJsonChanges() {
  8. return this.testjson.key1 != 'value1';
  9. }
  10. }

字符串

相关问题