如何安装svelte_Card.svelte的跨组件状态管理

如何安装svelte

Svelte makes handling the state of a single component very easy.

Svelte使处理单个组件的状态非常容易。

But how do we pass state around across components?

但是,我们如何在组件之间传递状态呢?

使用道具传递状态 (Passing state around using props)

The first strategy is common to other UI frameworks and it’s passing state around using props, lifting the state up.

第一种策略是其他UI框架所共有的,它使用props传递状态,从而提升状态

When a component needs to share data with another, the state can be moved up in the components tree until there’s a common parent to those components.

当一个组件需要与另一个组件共享数据时,可以在组件树中将状态上移,直到这些组件有一个公共父级。

The state needs to be passed down until it reaches all the components that need this state information.

需要向下传递状态,直到到达需要此状态信息的所有组件为止。

This is done using props, and it’s a technique that I think is the best as it’s simple.

这是使用props完成的,并且我认为这是一种最好的技术,因为它很简单。

Check the Svelte Props tutorial for more on props.

查看Svelte Props教程,以获取有关道具的更多信息。

上下文API (The Context API)

There are cases where props are not practical. Perhaps 2 components are so distant in the components tree that we’d have to move state up to the top level component.

在某些情况下道具不实用。 在组件树中,也许2个组件之间的距离是如此之遥,以至于我们不得不将状态提升到顶级组件。

In this case, another technique can be used and it’s called context API, and it’s ideal when you want to let multiple components communicate with descendants, but you don’t want to pass props around.

在这种情况下,可以使用另一种技术,称为上下文API ,当您希望让多个组件与子代通信但又不想传递道具时,它是理想的选择。

The context API is provided by 2 functions which are provided by the svelte package: getContext and setContext.

上下文API由svelte包提供的2个函数提供: getContextsetContext

You set an object in the context, associating it to a key:

您在上下文中设置一个对象,并将其与键关联:

<script>
import { setContext } from 'svelte'

const someObject = {}

setContext('someKey', someObject)
</script>

Into another component you can use getContext to retrieve the object assigned to a key:

在另一个组件中,可以使用getContext检索分配给键的对象:

<script>
import { getContext } from 'svelte'

const someObject = getContext('someKey')
</script>

You can only use getContext to retrieve a key either in the component that used setContext, or in one if its descendants.

您只能使用getContext来检索使用setContext的组件中的键,如果使用其后代,则只能使用一个键。

If you want to let two components living in 2 different component trees communicate, there’s another tool for us: stores.

如果您想让位于2个不同组件树中的两个组件进行通信,那么还有另一种工具供我们使用: stores

使用Svelte商店 (Using Svelte stores)

Svelte stores are a great tool to handle your app state when components need to talk to each other without passing props around too much.

Svelte商店是一个很好的工具,可以在组件需要相互通信而又不会过多传递道具时处理您的应用程序状态。

You must first import writable from svelte/store:

您必须首先从svelte/store导入writable

import { writable } from 'svelte/store'

and create a store variable using the writable() function, passing the default value as the first argument:

并使用writable()函数创建存储变量,并将默认值作为第一个参数传递:

const username = writable('Guest')

This can be put into a separate file, which you can import into multiple components, for example called store.js (it’s not a component, so it can be in a .js file instead of .svelte:

可以将其放入一个单独的文件中,您可以将其导入多个组件,例如,称为store.js (它不是组件,因此可以位于.js文件而不是.svelte

import { writable } from 'svelte/store'
export const username = writable('Guest')

Any other component now loading this file can access the store:

现在正在加载此文件的任何其他组件都可以访问商店:

<script>
import { username } from './store.js'
</script>

Now the value of this variable can be set to a new value using set(), passing the new value as the first argument:

现在可以使用set()将此变量的值设置为新值,并将新值作为第一个参数传递:

username.set('new username')

And it can be updated using the update() function, which differs from set() because you don’t just pass the new value to it - you run a callback function that is passed the current value as its argument:

而且可以使用update()函数进行更新,该函数与set()不同,因为您不只是将新值传递给它-您运行的回调函数会将当前值作为其参数传递:

const newUsername = 'new username!'
username.update(existing => newUsername)

You can add more logic here:

您可以在此处添加更多逻辑:

username.update(existing => {
  console.log(`Updating username from ${existing} to ${newUsername}`)
  return newUsername
})

To get the value of the store variable once, you can use the get() function exported by svelte/store:

拿到店里变量的值一次 ,就可以使用get()的导出函数svelte/store

import { readable, get } from 'svelte/store'
export const username = writable('Guest')
get(username) //'Guest'

To create a reactive variable instead, that’s updated whenever it changes, you can prepend the store variable using $, in this example $username. Using that will make the component rerender whenever the stored value changes.

要创建React式变量(每当它更改时都会更新),可以使用$存放存储变量,在本示例中$username 。 只要存储值更改,使用该命令将使组件重新呈现。

Svelte considers $ to be a reserved value and will prevent you to use it for things that are not related to stores values (and which might lead to confusion), so if you are used to prepend DOM references using $, don’t do it in Svelte.

Svelte认为$是保留值,将阻止您将其用于与商店值不相关的事情(这可能导致混乱),因此,如果习惯于使用$前缀DOM引用,请不要这样做在Card.svelte。

Another option, best suited if you need to execute some logic when the variable changes, is to use the subscribe() method of username:

如果您需要在变量更改时执行一些逻辑,那么最适合的另一种选择是使用usernamesubscribe()方法:

username.subscribe(newValue => {
	console.log(newValue)
})

In addition to writable stores, Svelte provides 2 special kinds of stores: readable stores and derived stores.

除了可写存储外,Svelte还提供2种特殊类型的存储: 可读存储派生存储

苗条的可读商店 (Svelte Readable Stores)

Readable stores are special because they can’t be updated from the outside - there’s no set() or update() method. Instead, once you set the initial state, they can’t be modified from the outside.

可读存储很特殊,因为它们不能从外部进行更新-没有set()update()方法。 相反,一旦设置了初始状态,便无法从外部对其进行修改。

The official Svelte docs show an interesting example using a timer to update a date. I can think of setting up a timer to fetch resource from the network, perform an API call, get data from the filesystem (using a local Node.js server) or anything else that can be set up autonomously.

Svelte官方文档显示了一个有趣的示例,该示例使用计时器来更新日期。 我可以考虑设置一个计时器,以从网络获取资源,执行API调用,从文件系统获取数据(使用本地Node.js服务器)或其他任何可以自动设置的内容。

In this case instead of using writable() to initialize the store variable, we use readable():

在这种情况下,我们不是使用writable()来初始化存储变量,而是使用readable()

import { readable } from 'svelte/store'
export const count = readable(0)

You can provide a function after the default value, that will be responsible for updating it. This function receives the set function to modify the value:

您可以在默认值之后提供一个函数,该函数将负责更新它。 此函数接收set函数来修改值:

<script>
import { readable } from 'svelte/store'
export const count = readable(0, set => {
  setTimeout(() => {
    set(1)
  }, 1000)
})
</script>

In this case, we update the value from 0 to 1 after 1 second.

在这种情况下,我们会在1秒后将值从0更新为1。

You can setup an interval in this function, too:

您也可以在此功能中设置间隔:

import { readable, get } from 'svelte/store'
export const count = readable(0, set => {
  setInterval(() => {
	  set(get(count) + 1)
  }, 1000)
})

You can use this in another component like this:

您可以在另一个组件中使用它,如下所示:

<script>
import { count } from './store.js'
</script>

{$count}

Card.svelte派生商店 (Svelte Derived Stores)

A derived store allows you to create a new store value that depends on the value of an existing store.

派生商店允许您创建一个新的商店值,该值取决于现有商店的值。

You can do so using the derived() function exported by svelte/store, which takes as first parameter the existing store value, and as a second parameter a function, which receives that store value as its first parameter:

您可以使用svelte/store导出的derived()函数来执行此操作,该函数将现有存储值作为第一个参数,而将接收该存储值作为其第一个参数的函数作为第二个参数:

import { writable, derived } from 'svelte/store'

export const username = writable('Guest')

export const welcomeMessage = derived(username, $username => {
  return `Welcome ${$username}`
})
<script>
import { username, welcomeMessage } from './store.js'
</script>

{$username}
{$welcomeMessage}

翻译自: https://flaviocopes.com/svelte-state-management/

如何安装svelte

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值