【问题标题】:Svelte: How to import all stores from a file without listing them all?Svelte:如何从文件中导入所有商店而不列出所有商店?
【发布时间】:2021-07-25 20:50:12
【问题描述】:

是否可以在一行中从文件中导入所有导出的商店?而不是像这样列出它们:

    import { store1, store2, store3 } from './stores.js';

有没有办法做这样的事情:

    import { * } from './stores.js';

还是有其他解决方法? 如果不是,建议使用什么架构来避免这种需要?

【问题讨论】:

    标签: javascript svelte


    【解决方案1】:

    我不知道它是否满足您的需求,但您可以将所有商店导出到一个对象中

    //main.svelte
    <script>
        import stores from './stores.js';
        let count_value, store1_v, store2_v;
        stores.count.subscribe(value => {
            count_value = value;
        });
        stores.store1.subscribe(value => {
            store1_v = value;
        });
        stores.store2.subscribe(value => {
            store2_v = value;
        });
    </script>
    
    <h1>The count is {count_value}</h1>
    <h1>The count is {store1_v}</h1>
    <h1>The count is {store2_v}</h1>
    
    //stores.js
    import { writable } from 'svelte/store';
    
    export const count = writable(0);
    export const store1 = writable(4565465);
    export const store2 = writable(345);
    
    export default {
    count,
    store1,
    store2,
    }
    

    商店的另一种选择是

    //stores.js
    import { writable } from 'svelte/store';
    
    export default {
    count: writable(0),
    store1: writable(4565465),
    store2: writable(345),
    }
    

    【讨论】:

    • 够好了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    相关资源
    最近更新 更多