You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否直接在对象属性上使用$store语法?

关于嵌套Writable store的$语法使用问题

结论先行:没法直接通过object.property这类嵌套形式用$语法访问,必须先把嵌套的store单独提取成当前作用域的变量。

为什么那些写法无效?

Svelte的$语法是编译器层面的语法糖,它只认当前作用域里直接声明的store变量,识别不了藏在对象属性里的store。所以你试的$motor.profile、motor.$profile、$(motor.profile)这些写法,编译器都没办法判断motor.profile是个Writable store,自然就不生效。

正确的用法

就像你代码里写的,先把嵌套的store解构出来,变成当前作用域的变量,就能正常用$语法了:

export let motor: Motor;
// {
//     profile: Writable<string>
// }

// 有效:先提取为单独变量
let { profile } = motor;
console.log($profile);

如果不想解构,也可以直接调用store的subscribe方法取值,只是没$语法方便:

motor.profile.subscribe(val => {
    console.log(val);
});

内容的提问来源于stack exchange,提问作者kalkronline

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:50:34