随笔

Svelte

https://github.com/sveltejs/svelte

又一个前端框架,它的主打是没用Virtual Dom,对于响应式数据直接在编译阶段检测到,然后去更新dom,不同于react的rerender,vue的依赖检测。

基本代码

如下实例,比较简单明了

// index.svelte
<h1>
    {name}
</h1>
<script>
    let name = "abc";

    setTimeout(()=>{
        name = "123";
    }, 3000)
</script>

特殊语法

也有一些看起来比较神奇的,类似于 useEffect 的代码

$: if (count >= 10) {
    count = 9;
}

另外也有模版语法,有点似曾相识的感觉

{#if user.loggedIn}
    <button on:click={toggle}>
        Log out
    </button>
{/if}

组件嵌套

跟 WebComponent 一样,使用 Slot

<Card>
    Hello
</Card>

// Card.svelte
<div>
    <slot></slot>
</div>

数据共享

需要注意的是 store 使用变量的时候,前面要加 $ 符号。

// store.js
import { writable } from 'svelte/store';
function createCount() {
    const { subscribe, set, update } = writable(0);

    return {
        subscribe,
        increment: () => update(n => n + 1),
        decrement: () => update(n => n - 1),
        reset: () => set(0)
    };
}
export const count = createCount();

export const name = writable('world');

// App.svelte
<script>
    import { count, name } from './store.js';
    $name = "Hello";
</script>

<h1>The count is {$name}, {$count}</h1>

<button on:click={count.increment}>+</button>
<button on:click={count.decrement}>-</button>
<button on:click={count.reset}>reset</button>

父子组件

事件传递

比如一个弹窗,接收一个 onOk 事件

function handleOk(event) {
    let id = event.detail.id;
}

<Modal on:ok={handleOk} />

// Modal.svelte
<script>
    import { createEventDispatcher } from 'svelte';

    const dispatch = createEventDispatcher();

    function sayHello() {
        dispatch('ok', { id: 1 });
    }
</script>

Props

子组件 export 出去变量接收 props,感觉怪怪的

<Modal visible={true} width={600} />

// Modal.svelte
<script>
    export let visible = false, width;
</script>

除此之外,它的打包是基于你使用到了哪些代码,也就是说项目体量越大它的运行时代码越多。 另外还可以打包成支持 React 和 Vue 使用的组件,这意思就很明显了,用我来写组件或者简单页面吧!

本文链接:https://note.lilonghe.net//post/svelte.html

-- EOF --