簡體   English   中英

是否可以從外部 js 文件訪問 Svelte 商店?

[英]Is it possible to access Svelte store from external js files?

我想知道我是否能夠從 plain.js 文件訪問我的Svelte存儲值。

我正在嘗試編寫基於存儲值返回動態值的函數,以將它們導入任何組件。 但是在 plain.js 文件中,我不能只使用 $ 符號訪問存儲值。

使用存儲值並可用於多個組件的基本功能的快速示例:

//in .svelte

function add() {
    $counter = $counter + 1;
 }

編輯:改寫一下

編輯:找到了一個解決方案,但我真的不知道它是否真的優化過..

//in .js file

import { get } from "svelte/store";
import { counter } from "./stores";

export function add() {
    var counterRef = get(counter);
    counter.set(counterRef + 1);
}

是的,一點沒錯。

一方面,商店 API 非常簡單,沒有什么能阻止您自己訂閱商店以了解價值:

import myStore from './stores'

myStore.subscribe(value => {
  // do something with the new value
  // you could store it for future reference...
})

而且,如果您只想知道當前值,Svelte 有一個幫助程序,即get函數:

import { get } from 'svelte/store';

import myStore from './stores'

const value = get(myStore);

除了 rixo 的答案,實現add的更好方法是使用商店的update方法:

import { counter } from "./stores";

export function add() {
    counter.update(n => n + 1);
}

您還可以創建一個實現該邏輯的自定義商店

這不完全是您要求的(導入),但此方法的目的相同:您將商店作為參數傳遞,因此無需在 the.js 中導入您的商店

import {get} from 'svelte/store'
export function add(yourStore) {
   let _yourStore = get(yourStore)
   yourStore.set(_yourStore + 1)
}

然后你只需要在你的 Svelte 組件中導入你的商店。
它允許不關心 your.js 中的商店導入,而只關心您的組件。

許多 Svelte 商店示例不使用對象,所以這就是我如何讓它工作的。 這使用異步獲取將用戶的語言環境更新為0 想象一下pstats = {uid: 1, locale: 5} ...

import { pstats} from './stores.js'

export async function leave_locale() {
   return fetch(`./builds/leave`, {method: 'get'})
          .then(res => res.json())
          .then(res => {
                pstats.update((theStore) => {
                    return Object.assign(theStore, {locale: 0});
                })
            })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM