Jos*_*ain 13 javascript svelte svelte-store
我想知道我是否能够从一个普通的 .js 文件访问我的Svelte存储值。
我正在尝试编写返回基于存储值的动态值的函数,以将它们导入任何组件。但在一个普通的 .js 文件中,我不能只用 $ 符号访问存储值..
使用存储值并可用于多个组件的基本函数的快速示例:
//in .svelte
function add() {
$counter = $counter + 1;
}
Run Code Online (Sandbox Code Playgroud)
编辑:改写一下
编辑: 找到了一个解决方案,但我真的不知道它是否真的优化了..
//in .js file
import { get } from "svelte/store";
import { counter } from "./stores";
export function add() {
var counterRef = get(counter);
counter.set(counterRef + 1);
}
Run Code Online (Sandbox Code Playgroud)
rix*_*ixo 22
是的,一点没错。
一方面,商店 API 非常简单,没有什么可以阻止您自己订阅商店以了解价值:
import myStore from './stores'
myStore.subscribe(value => {
// do something with the new value
// you could store it for future reference...
})
Run Code Online (Sandbox Code Playgroud)
而且,如果您只想知道当前值,Svelte 有一个帮助程序,get函数:
import { get } from 'svelte/store';
import myStore from './stores'
const value = get(myStore);
Run Code Online (Sandbox Code Playgroud)
除了 rixo 的回答,更好的实现方式add是使用 store 的update方法:
import { counter } from "./stores";
export function add() {
counter.update(n => n + 1);
}
Run Code Online (Sandbox Code Playgroud)
您还可以创建一个实现该逻辑的自定义商店。