[Medium] 📄 Vue Basic & API
1. Can you describe the core principles and advantages of the framework Vue?
請描述 Vue 框架的核心原理和優勢
核心原理
Vue 是一個漸進式的 JavaScript 框架,其核心原理包含以下幾個重要概念:
1. 虛擬 DOM(Virtual DOM)
使用虛擬 DOM 來提升效能。它只會更新有變化的 DOM 節點,而不是重新渲染整個 DOM Tree。透過 diff 演算法比較新舊虛擬 DOM 的差異,只針對差異部分進行實際 DOM 操作。
// 虛擬 DOM 概念示意
const vnode = {
tag: 'div',
props: { class: 'container' },
children: [
{ tag: 'h1', children: 'Hello' },
{ tag: 'p', children: 'World' },
],
};
2. 資料雙向綁定(Two-way Data Binding)
使用雙向資料綁定,當模型(Model)更改時,視圖(View)會自動更新,反之亦然。這讓開發者不需要手動操作 DOM,只需關注資料的變化。
<!-- Vue 3 推薦寫法:<script setup> -->
<template>
<input v-model="message" />
<p>{{ message }}</p>
</template>
<script setup>
import { ref } from 'vue';
const message = ref('Hello Vue');
</script>
Options API 寫法
<template>
<input v-model="message" />
<p>{{ message }}</p>
</template>
<script>
export default {
data() {
return {
message: 'Hello Vue',
};
},
};
</script>
3. 組件化(Component-based)
將整個應用切分成一個個組件,意味著重用性提升,這對維護開發會更為省工。每個組件都有自己的狀態、樣式和邏輯,可以獨立開發和測試。
<!-- Button.vue - Vue 3 <script setup> -->
<template>
<button @click="handleClick">
<slot></slot>
</button>
</template>
<script setup>
const emit = defineEmits(['click']);
const handleClick = () => {
emit('click');
};
</script>
4. 生命週期(Lifecycle Hooks)
有自己的生命週期,當資料發生變化時,會觸發相應的生命週期鉤子,這樣就可以在特定的生命週期中,做出相應的操作。
<!-- Vue 3 <script setup> 寫法 -->
<script setup>
import { onMounted, onUpdated, onUnmounted } from 'vue';
onMounted(() => {
// 組件掛載後執行
console.log('Component mounted!');
});
onUpdated(() => {
// 資料更新後執行
console.log('Component updated!');
});
onUnmounted(() => {
// 組件卸載後執行
console.log('Component unmounted!');
});
</script>
5. 指令系統(Directives)
提供了一些常用的指令,例如 v-if、v-for、v-bind、v-model 等,可以讓開發者更快速地開發。
<template>
<!-- 條件渲染 -->
<div v-if="isVisible">顯示內容</div>
<!-- 列表渲染 -->
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
<!-- 屬性綁定 -->
<img :src="imageUrl" :alt="imageAlt" />
<!-- 雙向綁定 -->
<input v-model="username" />
</template>
6. 模板語法(Template Syntax)
使用 template 來撰寫 HTML,允許將資料透過插值的方式,直接渲染到 template 中。
<template>
<div>
<!-- 文字插值 -->
<p>{{ message }}</p>
<!-- 表達式 -->
<p>{{ count + 1 }}</p>
<!-- 方法呼叫 -->
<p>{{ formatDate(date) }}</p>
</div>
</template>
Vue 的獨有優勢(和 React 相比)
1. 學習曲線較低
對團隊成員彼此程度的掌控落差不會太大,同時在書寫風格上,由官方統一規定,避免過於自由奔放,同時對不同專案的維護也能更快上手。
<!-- Vue 的單檔案組件結構清晰 -->
<template>
<!-- HTML 模板 -->
</template>
<script>
// JavaScript 邏輯
</script>
<style>
/* CSS 樣式 */
</style>