sveltejs-cn / svelte-cn

Svelte 中文文档
https://sveltejs-cn.github.io/svelte-cn/
16 stars 0 forks source link

Element bindings 翻译校准 #35

Closed yuwanli closed 5 years ago

yuwanli commented 5 years ago

元素绑定

bind:property={variable}
bind:group={variable}
bind:this={dom_node}

数据通常从父级流向子级。bind:指令允许数据以另一种方式从子级流向父级。大多数的绑定是绑定在特定的元素。

最简单反映了属性的值的绑定,例如input.value

<input bind:value={name}>
<textarea bind:value={text}></textarea>

<input type="checkbox" bind:checked={yes}>

如果,属性值和属性名相同,也可以用简写的方式:

<!-- These are equivalent -->
<input bind:value={value}>
<input bind:value>

强制输入的值是数字;即使input.value是一个字符串,svelte将把它当作一个数字。如果输入为空或无效(当type="number"),则该值为 undefined

<input type="number" bind:value={num}>
<input type="range" bind:value={num}>

绑定相关元素

可以使用 bind:group 来让 input 一起工作

<script>
    let tortilla = 'Plain';
    let fillings = [];
</script>

<!-- grouped radio inputs are mutually exclusive -->
<input type="radio" bind:group={tortilla} value="Plain">
<input type="radio" bind:group={tortilla} value="Whole wheat">
<input type="radio" bind:group={tortilla} value="Spinach">

<!-- grouped checkbox inputs populate an array -->
<input type="checkbox" bind:group={fillings} value="Rice">
<input type="checkbox" bind:group={fillings} value="Beans">
<input type="checkbox" bind:group={fillings} value="Cheese">
<input type="checkbox" bind:group={fillings} value="Guac (extra)">

绑定 <select>

<select>绑定的值,对应的是 selected 的<option>上的value属性的值,该值可以是任何值(不仅仅是字符串,可以是 DOM 中出现的值)。

<select bind:value={selected}>
    <option value={a}>a</option>
    <option value={b}>b</option>
    <option value={c}>c</option>
</select>

<select multiple> 的表现和 checkbox 组一样:

<select multiple bind:value={fillings}>
    <option value="Rice">Rice</option>
    <option value="Beans">Beans</option>
    <option value="Cheese">Cheese</option>
    <option value="Guac (extra)">Guac (extra)</option>
</select>

<option>value,和<option> 中的文本内容相同,则 value 属性可以被省略。

<select multiple bind:value={fillings}>
    <option>Rice</option>
    <option>Beans</option>
    <option>Cheese</option>
    <option>Guac (extra)</option>
</select>

绑定媒体元素

媒体元素(audiovideo)有自己的一套绑定规则:

四个只读的属性

三个可以双向绑定的属性

<video
    src={clip}
    bind:duration
    bind:buffered
    bind:seekable
    bind:played
    bind:currentTime
    bind:paused
    bind:volume
></video>

绑定块级元素

块级元素有4个只读的绑定,其值的计算使用的技术方式和这个类似:

<div
    bind:offsetWidth={width}
    bind:offsetHeight={height}
>
    <Chart {width} {height}/>
</div>

绑定DOM节点

要获取一个 DOM 节点的引用,可以使用bind:this

<script>
    import { onMount } from 'svelte';

    let canvasElement;

    onMount(() => {
        const ctx = canvasElement.getContext('2d');
        drawStuff(ctx);
    });
</script>

<canvas bind:this={canvasElement}></canvas>