Vue 3 內置屬性語法知識點及案例代碼
Vue 3 提供了豐富的內置屬性,幫助開發者高效地構建用戶界面。以下將詳細介紹 Vue 3 的主要內置屬性,并結合詳細的案例代碼進行說明。每個案例代碼都包含詳細的注釋,幫助初學者更好地理解其用法。
1. data
知識點
data
: 用于定義組件的響應式數據。- 在 Vue 3 中,
data
必須是一個返回對象的函數。 - 響應式數據的變化會自動更新視圖。
案例代碼
<template><div><h1>{{ message }}</h1><button @click="updateMessage">更新消息</button></div>
</template><script>
export default {name: 'DataExample',data() {return {message: 'Hello, Vue 3!'};},methods: {updateMessage() {this.message = '消息已更新!';}}
};
</script><style scoped>
h1 {color: #42b983;
}
</style>
說明:
data
函數返回一個包含message
屬性的對象。- 點擊按鈕時,
updateMessage
方法會更新message
的值,視圖會自動刷新。
2. methods
知識點
methods
: 用于定義組件中的方法。- 方法中的
this
指向當前組件實例,可以訪問data
、props
等屬性。
案例代碼
<template><div><p>計數器: {{ count }}</p><button @click="increment">增加</button><button @click="decrement">減少</button></div>
</template><script>
export default {name: 'MethodsExample',data() {return {count: 0};},methods: {increment() {this.count++;},decrement() {this.count--;}}
};
</script><style scoped>
button {margin: 0 5px;
}
</style>
說明:
- 定義了兩個方法
increment
和decrement
,用于增加和減少count
的值。 - 按鈕點擊時調用相應方法,更新視圖。
3. computed
知識點
computed
: 用于定義計算屬性,基于依賴進行緩存。- 計算屬性只有在依賴發生變化時才會重新計算。
- 適用于需要基于現有數據計算出新數據的場景。
案例代碼
<template><div><p>原始價格: {{ price }} 元</p><p>折扣價格: {{ discountedPrice }} 元</p><button @click="increasePrice">增加價格</button></div>
</template><script>
export default {name: 'ComputedExample',data() {return {price: 100};},computed: {discountedPrice() {return this.price * 0.9; // 假設打9折}},methods: {increasePrice() {this.price += 10;}}
};
</script><style scoped>
button {margin-top: 10px;
}
</style>
說明:
discountedPrice
是一個計算屬性,基于price
計算折扣后的價格。- 當
price
變化時,discountedPrice
會自動更新。
4. watch
知識點
watch
: 用于監聽數據的變化,并在變化時執行相應的回調函數。- 適用于需要在數據變化時執行異步操作或復雜邏輯的場景。
案例代碼
<template><div><p>用戶名: {{ username }}</p><input v-model="username" placeholder="輸入用戶名" /><p v-if="isUsernameValid">用戶名有效</p><p v-else>用戶名無效</p></div>
</template><script>
export default {name: 'WatchExample',data() {return {username: '',isUsernameValid: false};},watch: {username(newVal) {if (newVal.length >= 3) {this.isUsernameValid = true;} else {this.isUsernameValid = false;}}}
};
</script><style scoped>
input {margin-top: 10px;padding: 5px;
}
</style>
說明:
watch
監聽username
的變化。- 根據
username
的長度更新isUsernameValid
的值。 - 輸入框內容變化時,視圖會根據
isUsernameValid
顯示相應的提示。
5. props
知識點
props
: 用于接收父組件傳遞的數據。- 可以是數組或對象,用于定義組件的接收屬性。
案例代碼
父組件
<template><div><ChildComponent :greeting="message" /></div>
</template><script>
import ChildComponent from './ChildComponent.vue';export default {name: 'ParentComponent',components: {ChildComponent},data() {return {message: '你好,Vue 3!'};}
};
</script>
子組件 (ChildComponent.vue
)
<template><div><h2>{{ greeting }}</h2></div>
</template><script>
export default {name: 'ChildComponent',props: {greeting: {type: String,required: true}}
};
</script><style scoped>
h2 {color: #35495e;
}
</style>
說明:
- 父組件通過
props
向子組件傳遞greeting
數據。 - 子組件通過
props
接收并使用該數據。
6. emit
知識點
emit
: 用于觸發自定義事件,向父組件傳遞數據或通知事件。- 子組件通過
emit
觸發事件,父組件監聽并處理事件。
案例代碼
子組件 (ChildComponent.vue
)
<template><div><button @click="notifyParent">通知父組件</button></div>
</template><script>
export default {name: 'ChildComponent',methods: {notifyParent() {this.$emit('child-event', '來自子組件的消息');}}
};
</script><style scoped>
button {padding: 5px 10px;
}
</style>
父組件
<template><div><h1>{{ message }}</h1><ChildComponent @child-event="handleChildEvent" /></div>
</template><script>
import ChildComponent from './ChildComponent.vue';export default {name: 'ParentComponent',components: {ChildComponent},data() {return {message: '等待子組件的消息...'};},methods: {handleChildEvent(payload) {this.message = payload;}}
};
</script><style scoped>
h1 {color: #42b983;
}
</style>
說明:
- 子組件通過
this.$emit
觸發child-event
事件,并傳遞一個字符串作為負載。 - 父組件監聽
child-event
事件,并調用handleChildEvent
方法處理事件。 - 父組件的
message
會根據子組件傳遞的負載進行更新。
7. v-model
知識點
v-model
: 用于在表單輸入元素和組件狀態之間創建雙向綁定。- 簡化了表單處理和數據綁定。
案例代碼
<template><div><input v-model="text" placeholder="輸入文本" /><p>輸入的內容: {{ text }}</p></div>
</template><script>
export default {name: 'VModelExample',data() {return {text: ''};}
};
</script><style scoped>
input {padding: 5px;margin-bottom: 10px;
}
</style>
說明:
v-model
雙向綁定text
數據和輸入框的值。- 輸入框內容變化時,
text
的值會實時更新,反之亦然。
8. v-bind
和 v-on
知識點
v-bind
: 用于動態綁定 HTML 屬性或組件的props
。v-on
: 用于綁定事件監聽器。
案例代碼
<template><div><img v-bind:src="imageUrl" alt="示例圖片" /><button v-on:click="changeImage">更換圖片</button></div>
</template><script>
export default {name: 'VBindVOnExample',data() {return {imageUrl: 'https://via.placeholder.com/150',images: ['https://via.placeholder.com/150','https://via.placeholder.com/200','https://via.placeholder.com/250']};},methods: {changeImage() {const index = Math.floor(Math.random() * this.images.length);this.imageUrl = this.images[index];}}
};
</script><style scoped>
img {width: 150px;height: 150px;margin-bottom: 10px;
}
button {padding: 5px 10px;
}
</style>
說明:
v-bind:src
動態綁定圖片的src
屬性。v-on:click
綁定點擊事件,調用changeImage
方法更換圖片。- 點擊按鈕時,隨機選擇一張圖片并更新
imageUrl
,圖片會實時更換。
9. v-if
和 v-for
知識點
v-if
: 根據條件渲染元素。v-for
: 用于遍歷數組或對象,渲染列表。
案例代碼
<template><div><h2>水果列表</h2><ul><li v-for="(fruit, index) in fruits" :key="index">{{ index + 1 }}. {{ fruit.name }}<button v-if="fruit.quantity > 0" @click="buyFruit(index)">購買</button><span v-else>已售罄</span></li></ul><p>總購買數量: {{ totalPurchased }}</p></div>
</template><script>
export default {name: 'VIfVForExample',data() {return {fruits: [{ name: '蘋果', quantity: 5 },{ name: '香蕉', quantity: 0 },{ name: '橘子', quantity: 3 }],totalPurchased: 0};},methods: {buyFruit(index) {if (this.fruits[index].quantity > 0) {this.fruits[index].quantity--;this.totalPurchased++;}}}
};
</script><style scoped>
ul {list-style-type: none;padding: 0;
}
li {margin: 5px 0;
}
button {margin-left: 10px;padding: 2px 5px;
}
</style>
說明:
- 使用
v-for
遍歷fruits
數組,渲染水果列表。 - 使用
v-if
判斷水果的quantity
是否大于 0,顯示“購買”按鈕或“已售罄”。 - 點擊“購買”按鈕時,減少對應水果的數量,并增加總購買數量。
10. provide
和 inject
知識點
provide
: 用于向子組件提供數據或方法。inject
: 用于在子組件中接收provide
提供的數據或方法。
案例代碼
祖先組件 (AncestorComponent.vue
)
<template><div><h1>祖先組件</h1><ChildComponent /></div>
</template><script>
import ChildComponent from './ChildComponent.vue';export default {name: 'AncestorComponent',components: {ChildComponent},provide() {return {ancestorMessage: '來自祖先組件的消息'};}
};
</script>
子組件 (ChildComponent.vue
)
<template><div><h2>子組件</h2><p>{{ ancestorMessage }}</p></div>
</template><script>
export default {name: 'ChildComponent',inject: ['ancestorMessage']
};
</script><style scoped>
h2 {color: #35495e;
}
</style>
說明:
- 祖先組件通過
provide
提供ancestorMessage
數據。 - 子組件通過
inject
接收ancestorMessage
,并在模板中使用。 - 這種方式可以實現跨層級組件間的數據共享。
總結
以上介紹了 Vue 3 中常用的內置屬性及其用法,包括 data
、methods
、computed
、watch
、props
、emit
、v-model
、v-bind
、v-on
、v-if
、v-for
、provide
和 inject
。每個知識點都配有詳細的案例代碼和注釋,幫助初學者更好地理解和應用這些屬性。
通過不斷實踐和深入學習,您將能夠熟練地使用這些屬性,構建功能豐富、響應式的 Vue 3 應用。