Vue 3 是一個現(xiàn)代化的前端框架,通過一系列簡單而強大的特性锄奢,使得構(gòu)建用戶界面變得更加高效失晴。以下是Vue 3的核心知識點,通過這些知識點拘央,你可以快速上手并運用 Vue 3涂屁。
創(chuàng)建你的應(yīng)用
Vue 3 推薦使用 Vite 來快速創(chuàng)建開發(fā)環(huán)境:
npm init vite-app <project-name>
cd <project-name>
npm install
npm run dev
模板語法
文本插值
<span> {{ msg }} </span>
<span v-text='msg'></span>
設(shè)置內(nèi)部 HTML
<span v-html='rawHTML'></span>
使用 JS 表達式
<span> {{ msg.split('').reverse().join('') }} </span>
指令
條件渲染
<div v-if='show'>顯示</div>
<div v-else-if='showElse'>顯示其他</div>
<div v-else>隱藏</div>
事件處理
<button @click='handleClick'>點擊我</button>
const handleClick = (event) => {
console.log(event.target);
};
列表渲染
<ul>
<li v-for='(item, index) in items' :key='index'>{{ item }}</li>
</ul>
雙向綁定
<input v-model='inputValue' />
綁定數(shù)據(jù)
簡單綁定
<div :id='dynamicId'></div>
綁定類和樣式
<div :class='{ active: isActive }'></div>
<div :style='{ margin: marginValue + "px" }'></div>
父子組件通信
父組件向子組件傳遞數(shù)據(jù)
<child-component :msg='parentMsg' @update='handleUpdate'></child-component>
子組件通過 emit 發(fā)送事件
// 子組件
context.emit('update', 'new value');
插槽 (Slots)
基本插槽
<!-- 子組件 -->
<div>
<slot></slot>
</div>
<!-- 父組件 -->
<child-component>
這里的內(nèi)容會替換插槽內(nèi)容
</child-component>
命名插槽
<!-- 子組件 -->
<div>
<slot name='header'></slot>
<slot></slot>
</div>
<!-- 父組件 -->
<child-component>
<template v-slot:header>頭部內(nèi)容</template>
默認(rèn)插槽內(nèi)容
</child-component>
組合 API (Composition API)
Vue 3 引入了 Composition API,使得邏輯組織更加靈活:
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
const count = ref(0);
const state = reactive({ message: 'Hello Vue 3' });
const increment = () => {
count.value++;
};
onMounted(() => {
console.log('Component mounted!');
});
</script>
<template>
<div>{{ state.message }}</div>
<button @click="increment">Count: {{ count }}</button>
</template>
生命周期鉤子
onMounted
import { onMounted } from 'vue';
setup() {
onMounted(() => {
console.log('組件掛載完成');
});
}
其他鉤子
- onBeforeMount
- onBeforeUpdate
- onUpdated
- onBeforeUnmount
- onUnmounted
計算屬性和偵聽器
計算屬性
<script lang="ts" setup>
import { ref, computed } from 'vue';
const a = ref(1);
const b = computed(() => a.value * 2);
</script>
<template>
<div>{{ b }}</div>
</template>
偵聽器
<script lang="ts" setup>
import { ref, watchEffect } from 'vue';
const site = ref('learnvue.co');
watchEffect(() => {
console.log(site.value);
});
</script>
通過以上內(nèi)容堪滨,你可以快速掌握 Vue 3 的核心知識胯陋,并開始構(gòu)建功能強大的前端應(yīng)用。對于更多詳細(xì)的用法和示例,可以參考官方文檔和相關(guān)教程遏乔。