Svelte中修改类实例属性后模板未更新问题求助
问题原因与解决方案
原因
Svelte的响应式系统依靠顶层变量的赋值操作追踪变化,但你直接修改的是类实例内部的propertyA属性,并未对顶层变量objectA进行重新赋值,所以Svelte无法检测到这个属性变更,也就不会更新模板内容。
解决方案
方案1:手动触发响应式更新
在修改属性后,对objectA进行一次冗余赋值,强制Svelte检测到变化:
<script lang="ts"> class MyClass { public propertyA: string; constructor(value: string) { this.propertyA = value; } public changePropertyAValue = (value: string) => { this.propertyA = value; console.log(this.propertyA); return this; }; } let objectA = new MyClass('First value'); </script> <button on:click="{() => { objectA.changePropertyAValue('My new value'); objectA = objectA; // 触发响应式更新 }}">My Button</button> <h2>{objectA.propertyA}</h2>
方案2:用Svelte响应式机制改造类
将类的属性替换为Svelte的writable存储,让属性变更自动触发响应式:
<script lang="ts"> import { writable } from 'svelte/store'; class MyClass { public propertyA = writable(''); constructor(value: string) { this.propertyA.set(value); } public changePropertyAValue = (value: string) => { this.propertyA.set(value); this.propertyA.subscribe(v => console.log(v))(); // 打印当前值 return this; }; } let objectA = new MyClass('First value'); </script> <button on:click="{() => { objectA.changePropertyAValue('My new value'); }}">My Button</button> <h2>{$objectA.propertyA}</h2> <!-- 使用$订阅存储值 -->
方案3:用反应式声明中转属性
通过$:声明一个反应式变量,追踪objectA.propertyA的变化,模板使用这个中转变量:
<script lang="ts"> class MyClass { public propertyA: string; constructor(value: string) { this.propertyA = value; } public changePropertyAValue = (value: string) => { this.propertyA = value; console.log(this.propertyA); return this; }; } let objectA = new MyClass('First value'); $: currentValue = objectA.propertyA; // 自动追踪属性变化 </script> <button on:click="{() => { objectA.changePropertyAValue('My new value'); }}">My Button</button> <h2>{currentValue}</h2>
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

