Vue 3 全局 API 語法知識點及案例詳解
Vue 3 提供了豐富的全局 API,用于創建應用實例、注冊全局組件、指令、插件等。以下將詳細介紹 Vue 3 的主要全局 API,并結合詳細的案例代碼進行說明。每個案例代碼都包含中文注釋,幫助初學者更好地理解。
目錄
- createApp
- app.mount()
- app.unmount()
- app.component()
- app.directive()
- app.use()
- app.config.globalProperties
- Vue.nextTick()
- Vue.set() 和 Vue.delete()
- Vue.computed()
- Vue.observable()
- Vue.mixin()
- Vue.version
1. createApp
語法
import { createApp } from 'vue';
const app = createApp(rootComponent, rootProps);
說明
createApp
用于創建一個新的 Vue 應用實例。它接受一個根組件和一個可選的根 props 對象作為參數。
案例代碼
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Vue 3 createApp 示例</title><script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
</head>
<body><div id="app"></div><script>// 導入 createAppconst { createApp } = Vue;// 定義根組件const App = {template: `<div><h1>{{ message }}</h1><button @click="updateMessage">點擊更新消息</button></div>`,data() {return {message: 'Hello, Vue 3!'};},methods: {updateMessage() {this.message = '消息已更新!';}}};// 創建 Vue 應用實例const app = createApp(App, { /* rootProps */ });// 掛載應用app.mount('#app');</script>
</body>
</html>
解釋
- 導入
createApp
: 從 Vue 中導入createApp
函數。 - 定義根組件: 使用一個包含模板、數據和方法的對象定義根組件。
- 創建應用實例: 使用
createApp
創建一個新的 Vue 應用實例,并傳入根組件。 - 掛載應用: 使用
app.mount('#app')
將應用掛載到頁面的#app
元素上。
2. app.mount()
語法
app.mount('#app');
說明
app.mount()
用于將 Vue 應用掛載到一個 DOM 元素上。它接受一個選擇器字符串或一個實際的 DOM 元素作為參數。
案例代碼
(與 createApp
示例相同)
解釋
- 掛載應用:
app.mount('#app')
將 Vue 應用掛載到<div id="app"></div>
上。
3. app.unmount()
語法
app.unmount();
說明
app.unmount()
用于卸載一個已掛載的 Vue 應用,銷毀所有相關的組件和事件監聽器。
案例代碼
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Vue 3 app.unmount 示例</title><script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
</head>
<body><div id="app"></div><button id="unmount">卸載應用</button><script>const { createApp } = Vue;const App = {template: `<div><h1>{{ message }}</h1><button @click="updateMessage">點擊更新消息</button></div>`,data() {return {message: 'Hello, Vue 3!'};},methods: {updateMessage() {this.message = '消息已更新!';}}};const app = createApp(App);app.mount('#app');// 卸載應用按鈕點擊事件document.getElementById('unmount').addEventListener('click', () => {app.unmount();alert('Vue 應用已卸載');});</script>
</body>
</html>
解釋
- 卸載應用: 點擊“卸載應用”按鈕后,調用
app.unmount()
卸載 Vue 應用,銷毀所有組件和事件監聽器。
4. app.component()
語法
app.component('組件名', 組件選項);
說明
app.component()
用于全局注冊一個組件,使其在應用的任何地方都可以使用。
案例代碼
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Vue 3 app.component 示例</title><script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
</head>
<body><div id="app"><my-button></my-button></div><script>const { createApp } = Vue;// 定義全局組件 MyButtonconst MyButton = {template: `<button @click="handleClick">點擊我</button>`,methods: {handleClick() {alert('按鈕被點擊了!');}}};// 創建應用并注冊全局組件const app = createApp({template: `<div><h1>全局組件示例</h1><my-button></my-button></div>`});app.component('my-button', MyButton);app.mount('#app');</script>
</body>
</html>
解釋
- 定義全局組件: 使用
app.component('my-button', MyButton)
全局注冊組件MyButton
。 - 使用全局組件: 在根組件的模板中使用
<my-button></my-button>
,無需額外導入。
5. app.directive()
語法
app.directive('指令名', 指令選項);
說明
app.directive()
用于全局注冊一個自定義指令,使其在應用的任何地方都可以使用。
案例代碼
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Vue 3 app.directive 示例</title><script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script><style>.focused {border: 2px solid blue;}</style>
</head>
<body><div id="app"><input v-focus type="text" placeholder="請輸入內容"></div><script>const { createApp } = Vue;// 定義全局指令 focusconst app = createApp({data() {return {message: 'Hello, Vue 3!'};}});app.directive('focus', {mounted(el) {el.focus();},updated(el) {el.focus();}});app.mount('#app');</script>
</body>
</html>
解釋
- 定義全局指令: 使用
app.directive('focus', { ... })
全局注冊指令v-focus
。 - 指令邏輯:
mounted
和updated
鉤子中調用el.focus()
,使元素獲得焦點。 - 使用指令: 在模板中使用
v-focus
指令,元素加載時會自動獲得焦點。
6. app.use()
語法
app.use(plugin, options);
說明
app.use()
用于安裝 Vue 插件。插件可以添加全局功能,如全局指令、組件、混入等。
案例代碼
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Vue 3 app.use 示例</title><script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script><script src="https://unpkg.com/vue-router@4"></script>
</head>
<body><div id="app"></div><script>const { createApp, ref } = Vue;const { createRouter, createWebHistory } = VueRouter;// 定義插件const myPlugin = {install(app, options) {app.config.globalProperties.$myMethod = () => {console.log('插件方法被調用');};}};// 創建應用并使用插件const app = createApp({template: `<div><h1>{{ message }}</h1><button @click="invokePlugin">點擊調用插件方法</button></div>`,data() {return {message: 'Hello, Vue 3!'};},methods: {invokePlugin() {this.$myMethod();}}});app.use(myPlugin);app.mount('#app');</script>
</body>
</html>
解釋
- 定義插件: 創建一個插件
myPlugin
,在install
方法中為app.config.globalProperties
添加$myMethod
方法。 - 使用插件: 使用
app.use(myPlugin)
安裝插件。 - 調用插件方法: 在組件的方法中通過
this.$myMethod()
調用插件中定義的方法。
7. app.config.globalProperties
語法
app.config.globalProperties.$propertyName = value;
說明
app.config.globalProperties
用于向 Vue 應用實例添加全局屬性,使其在所有組件中都可以訪問。
案例代碼
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Vue 3 app.config.globalProperties 示例</title><script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
</head>
<body><div id="app"><h1>{{ $greeting }}</h1><button @click="showGreeting">點擊顯示問候語</button></div><script>const { createApp } = Vue;const app = createApp({data() {return {message: 'Hello, Vue 3!'};},methods: {showGreeting() {alert(this.$greeting);}}});// 添加全局屬性 $greetingapp.config.globalProperties.$greeting = '歡迎使用 Vue 3!';app.mount('#app');</script>
</body>
</html>
解釋
- 添加全局屬性: 使用
app.config.globalProperties.$greeting = '歡迎使用 Vue 3!'
添加全局屬性$greeting
。 - 訪問全局屬性: 在組件中通過
this.$greeting
訪問全局屬性。
8. Vue.nextTick()
語法
Vue.nextTick(callback);
說明
Vue.nextTick()
接受一個回調函數,在下一次 DOM 更新循環之后執行該回調函數。常用于在數據變化后操作 DOM。
案例代碼
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Vue 3 Vue.nextTick 示例</title><script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
</head>
<body><div id="app"><h1 ref="title">{{ message }}</h1><button @click="updateMessage">點擊更新消息</button></div><script>const { createApp, ref, nextTick } = Vue;const app = createApp({setup() {const message = ref('Hello, Vue 3!');const title = ref(null);const updateMessage = () => {message.value = '消息已更新!';nextTick(() => {console.log('DOM 已更新');console.log(title.value.innerText);});};return {message,updateMessage,title};}});app.mount('#app');</script>
</body>
</html>
解釋
- 使用
nextTick
: 在updateMessage
方法中更新數據后,使用nextTick
確保 DOM 已更新,然后進行后續操作,如訪問更新后的 DOM 內容。
9. Vue.set() 和 Vue.delete()
語法
Vue.set(target, propertyName/index, value);
Vue.delete(target, propertyName/index);
說明
Vue.set()
和 Vue.delete()
用于向響應式對象中添加或刪除屬性,確保這些操作是響應式的。
案例代碼
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Vue 3 Vue.set 和 Vue.delete 示例</title><script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
</head>
<body><div id="app"><h1>{{ user.name }}</h1><h2>{{ user.age }}</h2><button @click="addAge">添加年齡</button><button @click="removeAge">刪除年齡</button></div><script>const { createApp, reactive, Vue } = Vue;const app = createApp({data() {return {user: reactive({ name: '張三' })};},methods: {addAge() {Vue.set(this.user, 'age', 25);},removeAge() {Vue.delete(this.user, 'age');}}});app.mount('#app');</script>
</body>
</html>
解釋
- 添加屬性: 使用
Vue.set(this.user, 'age', 25)
向響應式對象user
中添加age
屬性。 - 刪除屬性: 使用
Vue.delete(this.user, 'age')
從user
中刪除age
屬性。 - 響應式更新: 這些操作確保
user
對象的變化是響應式的,視圖會自動更新。
10. Vue.computed()
語法
const computedProperty = computed(() => { /* 計算邏輯 */ });
說明
Vue.computed()
用于創建計算屬性,基于依賴進行緩存,只有在相關依賴發生變化時才會重新計算。
案例代碼
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Vue 3 Vue.computed 示例</title><script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
</head>
<body><div id="app"><h1>{{ fullName }}</h1><button @click="changeName">更改名字</button></div><script>const { createApp, reactive, computed } = Vue;const app = createApp({setup() {const user = reactive({firstName: '李',lastName: '四'});const fullName = computed(() => {return `${user.firstName} ${user.lastName}`;});const changeName = () => {user.firstName = '王';};return {user,fullName,changeName};}});app.mount('#app');</script>
</body>
</html>
解釋
- 定義計算屬性: 使用
computed
定義fullName
計算屬性,基于user.firstName
和user.lastName
計算。 - 響應式更新: 當
user.firstName
或user.lastName
發生變化時,fullName
會自動更新。
11. Vue.observable()
語法
const observableObject = Vue.observable({ /* 對象 */ });
說明
Vue.observable()
用于將一個普通對象轉換為響應式對象,使其在 Vue 應用中具有響應式特性。
案例代碼
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN>
<head><meta charset="UTF-8"><title>Vue 3 Vue.observable 示例</title><script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
</head>
<body><div id="app"><h1>{{ state.count }}</h1><button @click="increment">點擊增加</button></div><script>const { createApp, Vue } = Vue;const state = Vue.observable({ count: 0 });const app = createApp({setup() {const increment = () => {state.count++;};return {state,increment};}});app.mount('#app');</script>
</body>
</html>
解釋
- 創建響應式對象: 使用
Vue.observable({ count: 0 })
創建一個響應式對象state
。 - 修改狀態: 通過
state.count++
修改count
的值,視圖會自動更新。
12. Vue.mixin()
語法
Vue.mixin(mixin);
說明
Vue.mixin()
用于全局混入一個對象,混入對象的選項會被合并到每個組件的選項中。
案例代碼
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Vue 3 Vue.mixin 示例</title><script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
</head>
<body><div id="app"><h1>{{ message }}</h1><h2>{{ sharedData }}</h2></div><script>const { createApp, Vue } = Vue;// 定義混入對象const myMixin = {data() {return {sharedData: '這是混入的數據'};},created() {console.log('混入的 created 鉤子');}};const app = createApp({mixins: [myMixin],data() {return {message: 'Hello, Vue 3!'};},created() {console.log('組件的 created 鉤子');}});app.mount('#app');</script>
</body>
</html>
解釋
- 定義混入對象: 使用
myMixin
定義一個包含data
和created
鉤子的混入對象。 - 使用混入: 在組件中通過
mixins: [myMixin]
使用混入對象。 - 合并邏輯: 混入對象的
data
和created
鉤子會被合并到組件中,共享數據sharedData
可以在組件中使用。
13. Vue.version
語法
console.log(Vue.version);
說明
Vue.version
返回當前 Vue 版本的字符串。
案例代碼
<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Vue 3 Vue.version 示例</title><script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
</head>
<body><div id="app"><h1>當前 Vue 版本: {{ version }}</h1></div><script>const { createApp, ref, Vue } = Vue;const app = createApp({setup() {const version = ref(Vue.version);return {version};}});app.mount('#app');</script>
</body>
</html>
解釋
- 獲取版本號: 使用
Vue.version
獲取當前 Vue 版本,并將其賦值給version
變量。 - 顯示版本號: 在模板中顯示
version
的值。
總結
以上介紹了 Vue 3 的主要全局 API 及其用法。通過這些 API,開發者可以更高效地構建和管理 Vue 應用。理解并掌握這些全局 API 對于深入學習 Vue 3 是至關重要的。希望這些示例代碼和解釋能幫助你更好地理解 Vue 3 的全局 API。