在第 9 天,我將示範在 Vue 3、SvelteKit 和 Angular 中屬性綁定(attribute binding)的範例。範例中 Save Item 按鈕會在輸入長度至少為 5 之前被禁用。
<script setup lang="ts">
import { Icon } from '@iconify/vue'
import { ref } from 'vue'
const newItem = ref('')
const isEditing = ref('false')
const saveItem = () => { … same logic as before … }
</script>
<template>
<form v-if="isEditing" @submit.prevent="saveItem">
<input v-model.trim="newItem" placeholder="Add new item" />
<button :disabled="newItem.length < 5" aria-label="Save Item">
<Icon icon="ic:outline-save" />
</button>
</form>
</template>
從 Vue 3.4 版本開始,元素屬性綁定的語法為:
:<attribute name>=<value>
在此範例中,我們希望綁定 Save Item 按鈕的 disabled
屬性,使得當 newItem
這個 ref 的長度小於 5 時,按鈕會被禁用。
:disabled="newItem.length < 5"
會在輸入長度不足五時禁用按鈕。反之,按鈕便可使用,點擊以新增項目。
<script lang="ts">
import Icon from '@iconify/svelte';
let newItem = $state('');
let isEditing = $state(false);
function saveItem() { … same logic as before … }
</script>
{#if isEditing}
<form method="POST" onsubmit={handleSubmit}>
<input id="newItem" name="newItem" type="text" placeholder="Add item" bind:value={newItem} />
<button disabled={newItem.length < 5} aria-label="Save Item">
<Icon icon="ic:outline-save" />
</button>
</form>
{/if}
在 Svelte 5 中,元素屬性綁定方式與原生 JavaScript 相同。元素屬性可直接用 <attribute name>=<value>
的方式綁定。
在此範例中,我們將綁定儲存按鈕的 disabled
屬性,使其在 newItem
rune 字串長度小於 5 時禁用。
disabled={newItem.length < 5}
會在輸入長度不足五時禁用按鈕。反之,按鈕會啟用,可以點擊來新增項目。
import { ChangeDetectionStrategy, Component, computed, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { NgIcon, provideIcons } from '@ng-icons/core';
import { matSave } from '@ng-icons/material-icons/baseline';
@Component({
selector: 'app-shopping-cart',
imports: [FormsModule, NgIcon],
viewProviders: [provideIcons({ matSave })],
template: `
@if (isEditing()) {
<form (ngSubmit)="saveItem()">
<input type="text" placeholder="Add new item" name="newItem" [(ngModel)]="newItem" />
<button type="submit" [disabled]="newItem().length < 5" aria-label="Save Item">
<ng-icon name="matSave"></ng-icon>
</button>
</form>
}
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ShoppingCartComponent {
newItem = signal('');
isEditing = signal(false);
saveItem() { … same logic as before … }
}
在 Angular 中,使用方括號 ([]) 語法來綁定元素屬性。元素屬性可用 [attribute name]=<值>
的方式綁定。
此範例中,我們綁定儲存按鈕的 disabled
屬性,使得當 newItem
signal 的字串長度小於 5 時,按鈕會被禁用。
[disabled]="newItem.length < 5"
會在輸入長度不足五時禁用按鈕。反之,按鈕會啟用,可以點擊來新增項目。
Vue 3 屬性綁定教學:https://vuejs.org/guide/essentials/template-syntax.html#attribute-bindings
Svelte 屬性綁定教學:https://svelte.dev/docs/svelte/basic-markup#Element-attributes
Angular 屬性綁定教學:https://angular.dev/guide/templates/binding#binding-dynamic-properties-and-attributes
我們已成功更新購物車元件,使 Save Item 按鈕能根據條件動態綁定並啟用或禁用。