Svelte 綁定Store

2023-02-21 16:43 更新

如果 store可寫入的(即具有set方法),則可以綁定其值,就像可以綁定局部組件狀態(tài)一樣。

在此示例中,我們有一個(gè)可寫 storename和一個(gè)派生store greeting,嘗試更改<input>標(biāo)簽:

<input bind:value={$name}>

現(xiàn)在,更改name的輸入值 ,其值和依賴項(xiàng)都將獲得更新。

我們還可以直接分配store值在組件內(nèi)部,嘗試添加<button> 標(biāo)簽:

<button on:click="{() => $name += '!'}">
	Add exclamation mark!
</button>

此處 $name += '!' 相當(dāng)于 name.set($name + '!')

示例代碼

  • App.svelte

<script>
	import { name, greeting } from './stores.js';
</script>

<h1>{$greeting}</h1>
<input value={$name}>

  • stores.js

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

export const name = writable('world');

export const greeting = derived(
	name,
	$name => `Hello ${$name}!`
);


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)