如何安装svelte_Svelte的可读写商店入门

news/2024/7/7 15:46:31

如何安装svelte

If you’re familiar with Redux or Vuex, then the Svelte stores offer a similar feature for state management. If your app is getting complicated, then it becomes difficult for components to relay data between themselves. Moving it to a global data store is a better option. Here, we’ll look at two store options that Svelte makes available: writable stores and readable stores.

如果您熟悉Redux或Vuex,那么Svelte商店提供了类似的状态管理功能。 如果您的应用变得越来越复杂,则组件之间很难在它们之间中继数据。 将其移动到全局数据存储是一个更好的选择。 在这里,我们将看看Svelte提供的两个商店选项: 可写商店和可读商店 。

可写存储 (Writable Store)

Let’s go ahead and create a global state management file in our Svelte project - let’s call it store.js and import the writable function.

让我们继续在Svelte项目中创建一个全局状态管理文件-我们将其store.js并导入writable函数。

import { writable } from "svelte/store";

let counter = writable(1);

export {counter}

We’ve created a variable called counter, which is a writable store. counter now has the following self-explanatory methods:

我们创建了一个名为counter的变量,这是一个可写的存储区。 counter现在具有以下不言自明的方法:

  • set

    set

  • update

    update

Let’s create a custom component called Nested.svelte and use the counter store we just created.

让我们创建一个名为Nested.svelte的自定义组件,并使用刚刚创建的counter存储。

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

<div>
 counter value: {$counter}
</div>

Notice that during usage, we prefix the the variable with $, since this is a named import.

注意,在使用过程中,我们给变量加上$前缀,因为这是一个命名的import。

Let’s wrap it up by importing the component in the App.svelte file and create a method to write the counter variable to observe reactivity across nested components.

让我们通过将组件导入App.svelte文件中来进行App.svelte并创建一种方法来编写counter变量,以观察嵌套组件之间的React性。

<script>
import Nested from "./Nested.svelte";
import { counter } from "./store.js";

function incrementCounter() {
  counter.update(n => n + 1);
}
</script>

<div>
<button on:click={incrementCounter}>Update</button>
<Nested />
</div>

the counter uses an update method that takes a function whose parameter is the current value of the writable store and returns the modified value. If we run this app, we should be able to see the value inside the Nested component getting updated as we click on the button.

counter使用一种update方法,该方法采用一个函数,该函数的参数是可写存储的当前值,并返回修改后的值。 如果运行此应用程序,则单击按钮时,我们应该能够看到Nested组件中的值正在更新。

While we’re at it, let’s go ahead and add a reset button to App.svelte.

在此过程中,让我们继续,向App.svelte添加一个reset按钮。

function resetCounter() {
  counter.set(1);
}
<button on:click={resetCounter}>Reset</button>

The resetCounter uses the set method of our writable store.

resetCounter使用我们可写存储的set方法。

Now, the writable function also supports a second argument which is also a function. Here’s the signature for that function:

现在, writable函数还支持第二个参数,它也是一个函数。 这是该功能的签名:

writable(value: any, (set: (value: any) => void) => () => void)

This function is fired when the first subscriber is created and it returns another function that is fired when the last subscription to the variable is destroyed. Let’s see that in action.

当创建第一个订阅者时将触发此函数,并返回在最后一次对该变量的订阅被销毁时将触发的另一个函数。 让我们看看实际情况。

In our store.js, add the second argument to the writable function:

在我们的store.js ,将第二个参数添加到可写函数中:

let counter = writable(1, () => {
  console.log("First subscriber added!");
  return () => {
    console.log("Last subscriber deleted :(");
  };
});

To test this, we’ll mount and unmount the Nested component to observe the behavior, in App.svelte:

为了测试这一点,我们将在App.svelte安装和卸载Nested组件以观察其行为:

<script>
// ...
let flag = false;
function toggleMount() {
    flag = !flag;
}
</script>

  <!-- ... -->

  <button on:click={toggleMount}>Mount/Unmount</button>

  {#if flag}
    <Nested />
  {/if}
</div>

可读商店 (Readable Store)

Svelte also offers the readable function, which allows for creating readable stores whose values cannot be updated from other components. The value has to set from within the store. Let’s try this out, modify the store.js -

Svelte还提供了readable功能,该功能允许创建其值无法从其他组件更新的可读存储。 该值必须在商店内set 。 让我们尝试一下,修改store.js

import { readable } from "svelte/store";

let initialVal = Math.floor(Math.random()*100);

let counter = readable(initialVal, (set) => {
  let incrementCounter = setInterval( () => {
    let newVal = Math.floor(Math.random()*100);
    set(newVal);
  }, 1000);
  return () => {
    clearInterval(incrementCounter);
  };
});

export {counter}

Here the readable counter is set with the initialVal, which is being passed as the first argument. The second argument is the same as with writable stores, but this time it’s a required parameter since without it there would be no other way to access the counter value to reset it.

在这里, readable计数器设置为initialVal ,它将作为第一个参数传递。 第二个参数与可写存储区相同,但这一次它是必需的参数,因为如果没有它,将没有其他方法来访问counter值以将其重置。

In this example, we generate random numbers between 0 to 100 and assign this to counter by using the set method. update is not available. This is a simple demo, but in real apps readable stores can use the second argument to make API calls and, based on some logic, set the value. This will render the components that are subscribed to this store.

在此示例中,我们生成0到100之间的随机数,并使用set方法将其分配给counterupdate不可用。 这是一个简单的演示,但是在实际应用中,可读存储可以使用第二个参数进行API调用,并根据某些逻辑set该值。 这将呈现已订阅此商店的组件。



As you saw, by using writable and readable stores in Svelte, we can achieve a basic form of global state management pretty easily! ✨

如您所见,通过在Svelte中使用writablereadable存储,我们可以轻松实现全局状态管理的基本形式! ✨

翻译自: https://www.digitalocean.com/community/tutorials/svelte-svelte-store

如何安装svelte


http://www.niftyadmin.cn/n/3648836.html

相关文章

Android URI详解

就Android平台而言&#xff0c;URI主要分三个部分&#xff1a;scheme, authority and path。其中authority又分为host和port。格式如下&#xff1a; scheme://host:port/path 举个实际的例子&#xff1a; content://com.example.project:200/folder/subfolder/etc \---------/ …

Fragment的使用封装

封装类 public class FragmentManagerHelper {// 管理类FragmentManagerprivate FragmentManager mFragmentManager;// 容器布局id containerViewIdprivate int mContainerViewId;/*** 构造函数* param fragmentManager 管理类FragmentManager* param containerViewId 容器布局…

android APN解析

APN整理 前段时间&#xff0c;为公司项目添加APN设置功能。现在做一些整理&#xff0c;作为分享&#xff0c;作为笔记。 APN的字段 不同的手机&#xff0c;他们存放apn相关数据的字段是不一样的&#xff0c;这里表示出来的字段都是他们公有的部分。 publicclass APN { …

Symbian中的iScanCode和iCode

我们知道在Symbian的按键事件处理中使用以下方法:TKeyResponse CMegajoyContainer::OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType)这个方法是在CCoeControl(Control base class from which all other controls are derived)中定义的虚函数,其定义如下:Off…

如何在Ubuntu 18.04上使用Apache设置密码身份验证

介绍 (Introduction) As a web administrator, you may find it valuable to restrict some parts of a website from visitors, whether temporarily or on a permanent basis. While web applications may provide their own authentication and authorization methods, you …

Java疑惑点解析(二)

用过C的人都知道,C中有个"拷贝构造函数"的概念。这个概念是为了解决C中把一个对象指针赋值给另外一个对象指针,从而两个指针指向同一块内存区域而提出的。 同样,Java做为一门高级语言,它也无法避免这样的问题。Java中没有"拷贝构造函数"的概念,而是…

android开发中的权限与权限获取

访问登记属性android.permission.ACCESS_CHECKIN_PROPERTIES &#xff0c;读取或写入登记check-in数据库属性表的权限获取错略位置android.permission.ACCESS_COARSE_LOCATION&#xff0c;通过WiFi或移动基站的方式获取用户错略的经纬度信息&#xff0c;定位精度大概误差在30~1…

拦截Activity的启动流程绕过AndroidManifest检测

首先非常简单启动activity public void skip(View view){Intent intentnew Intent(this,TestActivity.class);startActivity(intent);} 这里TestActivity没有进行注册 HookStartActivityUtil工具封装类 public class HookStartActivityUtil {private String TAG "HookS…