首页 > 其他 > 详细

怎样在 Svelte 中使用 getters: derived

时间:2021-06-10 14:01:27      阅读:18      评论:0      收藏:0      [点我收藏+]

正文

Svelte 中的 store 不仅有 state,也可以有 getters,不过名字叫:derived,不太好读,但英文意思很直观:衍生的,也就是说,经他生成的数据是由其他 state 衍生的,这其实就是 getters 的定义,而 getters 也可以理解成 store 中的计算属性,也就是 computed,即 Svelte 中的:$: 开头的变量。

下面通过一个计数器演示 derived 的用法:

首先在 store.js 中定义并导出:

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

// state
export const count = writable(0)

// getters
export const dbCount = derived(count, $count => $count * 2)

然后在组件中使用:

<script>
  import {count, dbCount} from ‘./store.js‘
  const increment = () => count.update((val) => val + 1)
</script>

<button on:click={increment}> {$count} - {$dbCount} </button>

很自然,对吗!

参考

https://www.sveltejs.cn/tutorial/derived-stores

怎样在 Svelte 中使用 getters: derived

原文:https://www.cnblogs.com/ujiu/p/14870616.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!