當使用者進入編輯模式 (如列表項可刪除、排序、編輯),需要額外控制項。模式切換特效透過「滑動位移 + 工具列滑入」雙重動畫,強調新控制項的重要性,並保持空間連貫性。
<script setup>
import { ref, computed } from 'vue';
const props = defineProps({
items: Array,
editable: { type: Boolean, default: true }
});
const editingId = ref(null);
const itemWidth = ref(0); // 動態計算工具列寬度
const itemStyle = (id) => {
if (editingId.value !== id) return {};
const offset = `-${itemWidth.value}px`;
return { transform: `translateX(${offset})` };
};
const actionsStyle = (id) => {
if (editingId.value !== id) return { transform: 'translateX(100%)' };
return { transform: 'translateX(0)' };
};
function enterEdit(id, el) {
if (!props.editable) return;
itemWidth.value = el.querySelector('.item-actions').offsetWidth;
editingId.value = id;
}
function leaveEdit() {
editingId.value = null;
}
function handleAction(action, item) {
// 觸發父組件事件或直接處理
$emit(action, item);
if (action === 'delete') leaveEdit(); // 刪除後自動關閉
}
</script>
<template>
<ul class="editable-list">
<li v-for="item in items" :key="item.id" class="list-item">
<div class="item-content" :style="itemStyle(item.id)" @click="enterEdit(item.id, $el)">
<slot :item="item">{{ item.label }}</slot>
</div>
<div class="item-actions" :style="actionsStyle(item.id)">
<button @click.stop="handleAction('edit', item)" aria-label="編輯">✎</button>
<button @click.stop="handleAction('delete', item)" aria-label="刪除" class="destructive">🗑</button>
<button @click.stop="leaveEdit" aria-label="完成">✓</button>
</div>
</li>
</ul>
</template>
<style scoped>
.list-item {
position: relative;
overflow: hidden;
background: white;
border-bottom: 1px solid #eee;
}
.item-content {
display: flex; align-items: center; padding: 1rem;
transition: transform 0.25s cubic-bezier(0.25, 0.46, 0.45, 0.94);
cursor: pointer;
}
.item-actions {
position: absolute;
top: 0; right: 0; bottom: 0;
display: flex; align-items: center; gap: 0.5rem;
padding: 0 1rem;
background: #fff5f5;
border-left: 1px solid #fed7d7;
transition: transform 0.25s cubic-bezier(0.25, 0.46, 0.45, 0.94);
will-change: transform;
}
.item-actions button {
background: none; border: none; font-size: 1.2rem; cursor: pointer;
padding: 0.5rem; border-radius: 4px;
transition: background 0.15s;
}
.item-actions button:hover { background: #fee; }
.item-actions button.destructive { color: #e53e3e; }
</style>
| 決策點 | 選擇 | 理由 |
|---|---|---|
| 動畫驅動 | CSS Transform + Transition | GPU 加速、不觸發佈局、可被瀏覽器最佳化 |
| 緩動函數 | Material Design Standard Easing cubic-bezier(0.25, 0.46, 0.45, 0.94) | 自然、有機感、進場快離場慢 |
| 工具列寬度 | 動態測量 offsetWidth | 適應內容變化 (國際化、響應式)、避免硬編碼 |
| 單項編輯 | 同一時間僅一項進入編輯模式 | 避免認知負荷過高、簡化狀態管理 |
| 焦點管理 | 進入編輯聚焦首按鈕、退出回歸觸發元素 | 鍵盤/螢幕閱讀器可用 |
☰,配合 @dnd-kit/core 或 HTML5 Drag API。模式切換特效的核心在於「空間位移傳達狀態變化」。透過內容讓位、工具滑入的雙重動畫,使用者能瞬間理解:當前進入特定操作模式,完成後將回歸常態。這種空間敘事比單純顯示/隱藏更符合人類認知直覺。