Svelte:使组件对变量做出反应(重新渲染)

Hor*_*rst 3 javascript node.js svelte svelte-component svelte-3

我想每当“view.current”更改时重新渲染“Body”(我的 svelte 组件),以便它渲染相应的 .svelte 视图/组件:

应用程序.svelte

    <script>
    import Header from "./components/Header.svelte";
    import Footer from "./components/Footer.svelte";
    import Body from "./components/Body.svelte";

    import Login from "./views/Login.svelte";
    import Dashboard from "./views/Dashboard.svelte";

    import { view } from "./store";
</script>

<Header />
    <Body>
        {#if view.current === view.login}
            <Login />
        {:else if view.current === view.dashboard}
            <Dashboard />
        {/if}
    </Body>
<Footer />
Run Code Online (Sandbox Code Playgroud)

在“Body.svelte”中,我只有一个可以设计样式的插槽

身材苗条

    <div class="container">
    <div class="content">
        <slot></slot>
    </div>
</div>

<style>
    .container {
        padding: 1em;
        display: flex;
    }
    .content {
        margin: auto;
    }
</style>
Run Code Online (Sandbox Code Playgroud)

在 Login.svelte (和其他 svelte 组件)中,我想更改“view.current”:

登录.svelte

<script>
    import { view } from "../store";

    function handleLoginClick() {
        view.current = view.dashboard;
    }
</script>


<button type="button" on:click={handleLoginClick} class="btn btn-primary btn-lg login-btn">Login</button>

<style>
    .login-btn {
        display: block;
        margin: auto;
    }
</style>
Run Code Online (Sandbox Code Playgroud)

商店.js

    const user = {
    username: "",
    fullname: "",
    role: null,
    isLoggedIn: false
};

const view = {
    login: 1,
    dashboard: 2,
    current: 1
};

export {
    user,
    view
}
Run Code Online (Sandbox Code Playgroud)

“view.current”的值按预期更改,但“Body”不会更新/重新渲染。因此,无论“view.current”设置了什么,它总是显示login.svelte。有没有一种快速简便的方法可以使“Body”对“view.current”做出反应,以便它重新渲染,以便重新评估“App.svelte”中的 if/else 块?

Ste*_*aes 8

导入像组件中这样的常规变量会创建该变量的本地副本。您在登录中引用的内容view不与应用程序中的内容共享,因此更改不会反映在那里。

像跨组件一样共享状态的“Svelte-way”是使用store

在您的设置中,这意味着您首先将视图定义为商店:

import { writable } from 'svelte/store'

const view = writable({
    login: 1,
    dashboard: 2,
    current: 1
});
Run Code Online (Sandbox Code Playgroud)

在组件本身中,您必须为商店添加前缀$

<script>
    function handleLoginClick() {
        $view.current = $view.dashboard;
    }
</script>
Run Code Online (Sandbox Code Playgroud)
{#if $view.current === $view.login}
    <Login />
{:else if $view.current === $view.dashboard}
    <Dashboard />
{/if}
Run Code Online (Sandbox Code Playgroud)