使用 $ 表示法访问 svelte 商店导致引用错误 [英] Accessing svelte store with $ notation causing Reference Error
问题描述
我有一个 store.js
文件,其内容是:
I have a store.js
file whose content is :
import { writable } from 'svelte/store';
export const generateds = writable(0);
console.log("generateds", $generateds)
每次我尝试访问 $generateds(在此文件内部或外部)时,我都会收到此错误:
Each time I try to access $generateds (inside or outside this file) I get this error :
Uncaught ReferenceError: $generateds is not defined
at stores.js:4
at main.js:6
当我在新项目中使用商店时,没有问题.我在当前项目中找不到问题所在.
When I use a store in a new project, there is no problem. I can't find what's the problem in my current project.
这是我正在使用的 npm 包的列表:
Here is the list of the npm packages I'm using :
── @fortawesome/free-solid-svg-icons@5.14.0
├── @material/layout-grid@7.0.0
├── @mdi/js@5.9.55
├── @rollup/plugin-commonjs@17.1.0
├── @rollup/plugin-node-resolve@11.2.0
├── @smui/button@1.0.0
├── @smui/card@1.0.0
├── @smui/drawer@1.0.0
├── @smui/fab@1.0.0
├── @smui/icon-button@1.0.0
├── @smui/list@1.0.0
├── @smui/select@1.0.0
├── @smui/textfield@1.0.0
├── @smui/top-app-bar@1.0.0
├── @sveltejs/svelte-virtual-list@3.0.1
├── autoprefixer@9.8.6
├── dropzone@5.7.2
├── eslint-plugin-svelte3@2.7.3
├── eslint@7.9.0
├── firebase@7.24.0
├── firestore-export-import@0.10.0
├── mathlive@0.59.0
├── node-sass@4.14.1
├── postcss@8.2.6
├── query-string@6.13.2
├── rollup-plugin-analyzer@4.0.0
├── rollup-plugin-css-only@3.1.0
├── rollup-plugin-livereload@2.0.0
├── rollup-plugin-postcss@4.0.0
├── rollup-plugin-sass@1.2.2
├── rollup-plugin-svelte@7.1.0
├── rollup-plugin-terser@7.0.2
├── rollup@2.39.0
├── sass@1.32.7
├── sirv-cli@1.0.11
├── svelte-fa@2.1.1
├── svelte-loading-spinners@0.1.1
├── svelte-materialify@0.3.5
├── svelte-preprocess@4.6.9
├── svelte-routing@1.5.0
├── svelte@3.32.3
推荐答案
引用存储值的 $ 语法只能在 Svelte 组件中使用.来自文档(重点是我的):
The $ syntax to reference a store value can only be used inside a Svelte component. From the docs (emphasis mine):
任何时候你有一个 store 的引用,你都可以通过在它前面加上 $ 字符来访问它在组件内的值.这会导致 Svelte 声明前缀变量,并设置将在适当时取消订阅的商店订阅.
Any time you have a reference to a store, you can access its value inside a component by prefixing it with the $ character. This causes Svelte to declare the prefixed variable, and set up a store subscription that will be unsubscribed when appropriate.
如果您需要获取普通 JS 文件中的值,您可以订阅它 或使用 Svelte 的 get 函数(订阅存储以获取值并立即取消订阅).
If you need to get the value inside a normal JS file, you can either subscribe to it or use Svelte's get function (which subscribes to the store to get the value and immediately unsubscribes).
import { generateds } from './store.js';
import { get } from 'svelte/store';
// method 1
const unsubscribe = generateds.subscribe((val) => { console.log(val); });
unsubscribe();
// method 2
console.log(get(generateds));
这篇关于使用 $ 表示法访问 svelte 商店导致引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!