svelte教程(8)stores

简介: 有时,您将需要多个不相关的组件或常规的JavaScript模块访问这些值。在Svelte,我们通过store来做到这一点。store只是一种对象,该对象具有一种subscribe方法,该方法允许在store的value发生变化时通知订阅过的组件。

有时,您将需要多个不相关的组件或常规的JavaScript模块访问这些值。

在Svelte,我们通过store来做到这一点。store只是一种对象,该对象具有一种subscribe方法,该方法允许在store的value发生变化时通知订阅过的组件。

可写 store

通过 writable 方法可以创建一个可写store,传入两个参数value, start。

  • value:初始值
  • start:获得第一个订阅者时调用,拥有一个参数为set的回调。可以返回一个stop方法,该方法在最后一个订阅者退订时执行。
import { writable } from 'svelte/store';

export const count = writable(0,(set)=>{
  console.log('subscribe count')
  set(100)
  return ()=>{
    console.log('clear count')
  }
});

可读store拥有三个方法:update 、set、subscribe。

  • set: 设置value值。
  • update: 更新value值,接受一个参数为value的方法,return一个新的value值。
function update(fn) {
   set(fn(value));
}
  • subscribe: 订阅该store,接受一个参数为value的方法,用于获得value值并进行处理。返回值为一个退订方法,执行该方法完成退订。
<script>
  import { onDestroy } from "svelte";
  import { count } from "../stores";
  let count_value;
  const unsubscribe = count.subscribe(value => {
    count_value = value;
  });
  onDestroy(unsubscribe());
</script>

<h1>The count is {count_value}</h1>
<button
  on:click={() => {
    count.update(c => c - 1);
  }}>
  -
</button>
<button
  on:click={() => {
    count.update(c => c + 1);
  }}>
  +
</button>
<button
  on:click={() => {
    count.set(0);
  }}>
  reset
</button>

自动订阅

使用$进行自动订阅,自动订阅的store将在组件销毁时自动调用停止订阅方法。

<script>
  import { onDestroy } from "svelte";
  import { count } from "../stores";
</script>

<h1>The count is {$count}</h1>
<button
  on:click={() => {
    count.update(c => c - 1);
  }}>
  -
</button>
<button
  on:click={() => {
    count.update(c => c + 1);
  }}>
  +
</button>
<button
  on:click={() => {
    count.set(0);
  }}>
  reset
</button>

只读store

只读store就是没有暴露update、set方法的可写store。

import {
  readable
} from 'svelte/store';

export const time = readable(new Date(), function start(set) {
  const interval = setInterval(() => {
    set(new Date());
  }, 1000);

  return function stop() {
    clearInterval(interval);
  };
});
<script>
    import { time } from '../stores';

    const formatter = new Intl.DateTimeFormat('en', {
        hour12: true,
        hour: 'numeric',
        minute: '2-digit',
        second: '2-digit'
    });
</script>

<h1>The time is {formatter.format($time)}</h1>

派生store

您可以使用创建一个store,并且这个store基于其他一个或者多个store,可以使用派生store。

export const elapsed = derived(
  time,
  $time => Math.round(($time - start) / 1000)
);

derived接受三个参数:

  • stores:可以为一个store对象,或者为一个数组。
  • fn:接受一个方法包含两个参数values,set。如果stores为数组,values也为数组,如果stores为store对象,values为改store的value。如果没有set参数,派生store的value为fn的返回值,如果包含set参数可以使用set方法指定value值。
  • initial_value:初始值(异步时使用)

绑定 store

如果store是可写的(即它具有set方法),则可以绑定其值,就像可以绑定到本地组件一样。

也可以通过直接赋值将value写进store。

<input bind:value={$count}>

<button on:click="{() => $count += 1}">
    + 1
</button>

本教程的所有代码均上传到github有需要的同学可以参考 https://github.com/sullay/svelte-learn

目录
相关文章
|
4月前
|
前端开发 JavaScript SEO
【NextJs】NextJs是什么
什么是NextJs 首先查看NextJs官网给出了如下的解释(官网地址: nextjs.org): The React Framework for the Web. Used by some of the world's largest companies, Next.js enables you to create high-quality web applications with the power of React components 总结就是用的公司多,框架水平NB,经住了很多项目的磨练。然后官网就给出了NextJs学习教程,做一个Dashboard网站。 如果要看这个教程的话:可
81 1
|
4月前
Vuejs基础版VIII
Vuejs基础版VIII
|
12月前
|
JavaScript 前端开发 UED
单文件组件(Single-File Components):Vue.js开发的模块化之道
Vue.js是一款流行的JavaScript框架,以其简洁、灵活和易用而广受欢迎。其中一个Vue.js的强大功能就是单文件组件(Single-File Components),它使得Vue.js应用的开发更加模块化和可维护。在本博客中,我们将深入探讨单文件组件的概念、结构、用法,以及如何利用它们来构建清晰、可复用和高效的Vue.js应用。
160 0
|
前端开发 数据安全/隐私保护
React高阶组件(Higher-Order Components)及其应用
React高阶组件(Higher-Order Components)及其应用
73 0
react+hook+ts项目总结-ant design form autoComplete=“off“
react+hook+ts项目总结-ant design form autoComplete=“off“
102 0
|
前端开发 JavaScript
Components make life easier(组件复用让生活更美好)
Components and Props Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
86 0
|
前端开发
react项目实战学习笔记-学习9-ReactDOM.render is no longer supported in React 18
react项目实战学习笔记-学习9-ReactDOM.render is no longer supported in React 18
139 0
|
Web App开发 JavaScript 前端开发
Modern模式引发qiankun的一场“命案”
前沿:文章的起源在于开发环境中使用qiankun框架,父应用加载子应用遇到一则报错 Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec 直接的翻译意思就是加载模块脚本失败:服务器以非JavaScript MIME类型“text/html”去响应。而也是这个问题引发了我的思考,到底是什么问题导致?
960 0
Modern模式引发qiankun的一场“命案”
|
前端开发 JavaScript 数据库
react + Ant Design + 支持 markdown 的 blog-react 项目的文档说明
react + Ant Design + 支持 markdown 的 blog-react 项目的文档说明
293 0
react + Ant Design + 支持 markdown 的 blog-react 项目的文档说明
vue3初体验-provide/inject
vue3初体验-provide/inject
108 0