Svelte - 尝试访问 'store.js' returns 'undefined' 中的 'readable' 对象

Svelte - Trying to access a 'readable' object within 'store.js' returns 'undefined'

如下图所示,您可以访问正常的 Object(这是预料之中的)但不能访问 stores.js.[=23 中的 readable =]

App.svelte

<script>
    import { myStuff, myStuff2 } from './stores.js';
</script>

<h1>This is {$myStuff.TEST}</h1>
<h1>This is {myStuff2.TEST}</h1>

stores.js

import { readable } from 'svelte/store';

export const myStuff = readable({
    TEST: "HELLO"
});

export const myStuff2 = {
    TEST: "HELLO 2"
};

// Doesn't work
console.log("TEST FROM STORE: " + myStuff.TEST);

// Works
console.log("TEST FROM STORE: " + myStuff2.TEST);

为什么会这样?

Tutorial mentions briefly that you might get an undefiend but it doesn't elaborate much past that and the Docs 在撰写本文时并未提及可能的结果。

来自标记答案的示例屏幕截图:

您可以使用 get:

Generally, you should read the value of a store by subscribing to it and using the value as it changes over time. Occasionally, you may need to retrieve the value of a store to which you're not subscribed. get allows you to do so.

例如:

import { readable, get } from 'svelte/store';

console.log("TEST FROM STORE: " + get(myStuff).TEST);

存储在 Svelte 中的工作方式是它们将您的值包装在 class 中,它没有直接获取存储值的方法。您需要订阅它才能获得它。还有一个 get 方法在后台执行相同的操作。

所以在您的代码中,这将打印该值。它还会在更改时打印新值。

const unsub=mystuff.subscribe(val=> console.log("CURRENT VALUE OF TEST FROM STORE: " + val.TEST))
unsub()

//this does the same thing:
import { get } from 'svelte/store';
console.log("TEST FROM STORE: " + get(myStuff).TEST);

在 .svelte 文件中,$____ 符号为您进行此订阅以使其更方便地使用它。