怎样在 Svelte 中将 store 绑定到表单组件

正文

所谓表单组件就是跟用户有交互的、能取到值的、是 form 的表单项的组件。在 Vue、React 中,store 里面的数据是严格控制其变动方式的,store 中的 state 只能通过 commit 触发改变。而 Svelte 中的 store 的更新是“自带”的,通过 set、update 就可以实现,并且还能实现 store 与 表单控件的双向绑定。如下:

// store.js
import { writable } from 'svelte/store'

export const name = createName('World!')

function createName(defaultVal) {
  const { set, subscribe, update } = writable(defaultVal)
  return {
    set, // 绑定表单项时,set 是必要的
    subscribe,
    push(value) {
      update(val => val + value)
    },
  }
}
<!-- App.svelte -->
<script>
  import { name } from "./store.js";
</script>

<input type="text" bind:value={$name} />
<button on:click={() => name.push('!')}> 增加感叹号 </button>

这种灵活的写法是否会带来各种问题,我不知道,但尽量使用自定义 store,让其变更或修改变得稍微可控一点,不然感觉真有点 hold 不住。。。

参考

https://www.sveltejs.cn/tutorial/store-bindings

原文地址:https://www.cnblogs.com/aisowe/p/15245594.html