前端Vue3最常用的?20?道面試題總結(jié)(含詳細解釋和代碼示例)
前言
以下是老曹關(guān)于 Vue 3 最常用的 20 道面試題總結(jié),涵蓋 Vue 3 的核心特性如 Composition API、響應(yīng)式系統(tǒng)(ref / reactive)、生命周期鉤子、組件通信、Teleport、Suspense、自定義指令等高頻知識點。每道題都配有詳細解釋和代碼示例,適合用于前端開發(fā)崗位的 Vue 3 技術(shù)面試準備,大家可以碼住隨時翻出來查閱背誦和練習(xí)!
1. Vue 3 和 Vue 2 的區(qū)別是什么?
問題: 解釋 Vue 3 相比 Vue 2 的主要改進點。(最主要,不是全部,全部后續(xù)老曹會再擴展)
答案:
| 特性 | Vue 2 | Vue 3 |
|---|---|---|
| 響應(yīng)式系統(tǒng) | Object.defineProperty | Proxy |
| 架構(gòu) | 單一源碼 | 模塊化架構(gòu)(Tree-shakable) |
| Composition API | ? | ? |
| Fragment | ? | ? |
| Suspense 組件 | ? | ? |
| 自定義渲染器支持 | 有限 | 更靈活 |
| 支持 TypeScript | ?(需額外配置) | ? 原生支持 |
// Vue 3 示例:使用 Composition API
import { ref, onMounted } from 'vue';
export default {
setup() {
const count = ref(0);
function increment() {
count.value++;
}
onMounted(() => {
console.log('組件掛載');
});
return { count, increment };
}
};
2. 如何在 Vue 3 中創(chuàng)建一個響應(yīng)式對象?
問題: 使用 reactive() 創(chuàng)建一個響應(yīng)式用戶對象。
答案:
使用 reactive() 創(chuàng)建深層響應(yīng)式對象。
import { reactive } from 'vue';
const user = reactive({
name: 'Alice',
age: 25
});
3.ref()和reactive()的區(qū)別?
問題: 寫出兩者的不同點及適用場景。
答案:
ref():適用于基本類型或單個值。reactive():適用于對象或復(fù)雜結(jié)構(gòu)。
import { ref, reactive } from 'vue';
const count = ref(0); // 基本類型
const user = reactive({ name: 'Bob' }); // 對象
count.value++; // 必須用 .value
user.name = 'Tom'; // 不需要 .value
4. Vue 3 中如何監(jiān)聽數(shù)據(jù)變化?
問題: 使用 watchEffect 和 watch 的方式分別寫出監(jiān)聽邏輯。
答案:
watchEffect:自動追蹤依賴并執(zhí)行副作用。watch:手動指定監(jiān)聽的目標(biāo)。
import { ref, watchEffect, watch } from 'vue';
const count = ref(0);
// watchEffect
watchEffect(() => {
console.log('Count changed:', count.value);
});
// watch
watch(count, (newVal, oldVal) => {
console.log(`從 ${oldVal} 變?yōu)?${newVal}`);
});
5. Vue 3 的生命周期鉤子有哪些?如何使用?
問題: 在 setup() 中使用 onMounted 生命周期鉤子。
答案:
Vue 3 提供了與 Vue 2 類似的生命周期鉤子,但必須從 vue 導(dǎo)入使用。
import { onMounted } from 'vue';
export default {
setup() {
onMounted(() => {
console.log('組件已掛載');
});
}
};
6. Vue 3 中如何進行父子組件通信?
問題: 父組件向子組件傳遞數(shù)據(jù),并觸發(fā)事件。
答案:
使用 props接收父組件數(shù)據(jù),使用 emit 觸發(fā)事件。
// 子組件 Child.vue
export default {
props: ['title'],
emits: ['update'],
setup(props, { emit }) {
function handleClick() {
emit('update', 'New Value');
}
return { handleClick };
}
};
// 父組件 Parent.vue
<template>
<Child :title="msg" @update="handleUpdate" />
</template>
<script>
import Child from './Child.vue';
export default {
components: { Child },
data() {
return {
msg: 'Hello'
};
},
methods: {
handleUpdate(value) {
console.log('收到更新:', value);
}
}
};
</script>
7. Vue 3 的setup()函數(shù)的作用是什么?
問題: setup() 是什么?為什么它很重要?
答案:
setup()是 Vue 3 Composition API 的入口函數(shù)。- 替代 Vue 2 中的
data、methods、computed等選項。 - 更好地組織邏輯復(fù)用和模塊化代碼。
export default {
setup() {
const message = ref('Hello Vue 3');
function changeMessage() {
message.value = 'Updated!';
}
return { message, changeMessage };
}
};
8. Vue 3 中如何實現(xiàn)響應(yīng)式計算屬性?
問題: 使用 computed() 實現(xiàn)一個計算屬性。
答案:
使用 computed() 創(chuàng)建響應(yīng)式計算屬性。
import { ref, computed } from 'vue';
export default {
setup() {
const firstName = ref('John');
const lastName = ref('Doe');
const fullName = computed(() => `${firstName.value} ${lastName.value}`);
return { firstName, lastName, fullName };
}
};
9.provide()和inject()的作用是什么?
問題: 如何跨層級傳遞數(shù)據(jù)?
答案:
用于祖先組件向后代組件注入依賴,不通過 props 逐層傳遞。
// 祖先組件
import { provide, ref } from 'vue';
export default {
setup() {
const theme = ref('dark');
provide('theme', theme);
return { theme };
}
};
// 后代組件
import { inject } from 'vue';
export default {
setup() {
const theme = inject('theme');
return { theme };
}
};
10. Vue 3 中如何使用插槽(Slot)?
問題: 實現(xiàn)一個默認插槽和具名插槽。
答案:
<!-- 父組件 -->
<template>
<Card>
<template #default>這是默認插槽內(nèi)容</template>
<template #header>這是頭部插槽</template>
</Card>
</template>
<!-- 子組件 Card.vue -->
<template>
<div class="card">
<header><slot name="header"></slot></header>
<main><slot></slot></main>
</div>
</template>
11. Vue 3 中的Teleport有什么用途?
問題: 如何將模態(tài)框渲染到 <body> 下?
答案:Teleport 可以將組件渲染到 DOM 中任意位置。
<template>
<teleport to="body">
<div v-if="showModal" class="modal">這是一個模態(tài)框</div>
</teleport>
</template>12. Vue 3 中的Suspense是什么?怎么用?
問題: 異步加載組件時顯示加載狀態(tài)。
答案:Suspense 是一個內(nèi)置組件,用于處理異步依賴。
<template>
<suspense>
<template #default>
<AsyncComponent />
</template>
<template #fallback>
加載中...
</template>
</suspense>
</template>
<script>
const AsyncComponent = defineAsyncComponent(() => import('./MyComponent.vue'));
</script>13. Vue 3 中的defineProps和defineEmits是什么?
問題: 在 <script setup> 中如何聲明 props 和 emits?
答案:
在 <script setup> 中直接使用 defineProps 和 defineEmits。
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps(['title']);
const emit = defineEmits(['update']);
function updateTitle() {
emit('update', 'New Title');
}
</script>
<template>
<h1>{{ title }}</h1>
<button @click="updateTitle">更新標(biāo)題</button>
</template>
14. Vue 3 中如何動態(tài)綁定樣式?
問題: 動態(tài)設(shè)置背景顏色。
答案:
使用 :style 綁定對象。
<template>
<div :style="{ backgroundColor: color }">{{ text }}</div>
</template>
<script>
export default {
data() {
return {
color: 'lightblue',
text: '動態(tài)樣式'
};
}
};
</script>
15. Vue 3 中如何注冊全局組件?
問題: 注冊一個可全局使用的按鈕組件。
答案:
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import MyButton from './components/MyButton.vue';
const app = createApp(App);
app.component('MyButton', MyButton);
app.mount('#app');
<!-- 使用 --> <template> <my-button label="提交" /> </template>
16. Vue 3 中如何實現(xiàn)自定義指令?
問題: 實現(xiàn)一個高亮指令 v-highlight。
答案:
// main.js
import { createApp } from 'vue';
import App from './App.vue';
const app = createApp(App);
app.directive('highlight', {
mounted(el) {
el.style.backgroundColor = '#f0e68c';
}
});
app.mount('#app');
<!-- 使用 --> <template> <p v-highlight>這段文字被高亮了</p> </template>
17. Vue 3 中的nextTick()怎么用?
問題: 修改 DOM 后等待更新完成。
答案:
使用 nextTick() 確保 DOM 更新完成后執(zhí)行操作。
import { nextTick } from 'vue';
async function updateData() {
this.message = '更新后的內(nèi)容';
await nextTick();
console.log('DOM 已更新');
}
18. Vue 3 中如何實現(xiàn)組件懶加載?
問題: 使用異步組件實現(xiàn)路由懶加載。
答案:
使用 defineAsyncComponent 實現(xiàn)懶加載。
import { defineAsyncComponent } from 'vue';
const AsyncComponent = defineAsyncComponent(() =>
import('./components/LazyComponent.vue')
);
export default {
components: {
AsyncComponent
}
};
19. Vue 3 中的emitter是什么?如何使用?
問題: 實現(xiàn)非父子組件之間的通信。
答案:
使用第三方庫如 mitt 或 EventBus 實現(xiàn)全局通信。
npm install mitt
// eventBus.js
import mitt from 'mitt';
export const emitter = mitt();
// 發(fā)送事件
import { emitter } from './eventBus';
emitter.emit('update', 'Hello');
// 接收事件
import { emitter } from './eventBus';
emitter.on('update', (msg) => {
console.log(msg);
});
20. Vue 3 中如何使用v-model實現(xiàn)雙向綁定?
問題: 實現(xiàn)一個輸入框組件的雙向綁定。
答案:
使用 modelValue + update:modelValue。
<template>
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
/>
</template>
<script>
export default {
props: ['modelValue'],
emits: ['update:modelValue']
};
</script>
總結(jié)表格
| 編號 | 題目描述 | 知識點 | 示例代碼 | 常見考察點 |
|---|---|---|---|---|
| 1 | Vue3 與 Vue2 的區(qū)別 | 架構(gòu)升級 | Proxy, Composition API | 框架理解 |
| 2 | 創(chuàng)建響應(yīng)式對象 | reactive() | reactive({}) | 數(shù)據(jù)綁定 |
| 3 | ref() vs reactive() | 響應(yīng)式機制 | ref(0) vs reactive({}) | 數(shù)據(jù)封裝 |
| 4 | 數(shù)據(jù)監(jiān)聽 | watchEffect, watch | watch(count, () => {...}) | 數(shù)據(jù)驅(qū)動 |
| 5 | 生命周期鉤子 | onMounted, onUpdated | onMounted(() => {}) | 組件控制 |
| 6 | 組件通信 | [props]/ emit | defineProps(['name']) | 組件設(shè)計 |
| 7 | setup() 的作用 | Composition API 入口 | setup() { return {} } | 邏輯組織 |
| 8 | 計算屬性 | computed() | computed(() => a + b) | 響應(yīng)式優(yōu)化 |
| 9 | 跨級傳參 | provide/inject | provide('theme', 'dark') | 數(shù)據(jù)共享 |
| 10 | 插槽使用 | 默認插槽 / 具名插槽 | <slot name="header" /> | 組件擴展 |
| 11 | Teleport 的用途 | 渲染到其他節(jié)點 | <teleport to="body">...</teleport> | DOM 結(jié)構(gòu)優(yōu)化 |
| 12 | Suspense 的用途 | 異步加載 | <suspense><template #default>... | 異步組件 |
| 13 | <script setup> 中的 [props]/ emit | 快捷方式 | defineProps(['title']) | 新語法糖 |
| 14 | 動態(tài)綁定樣式 | :style | :style="{ color: textColor }" | 樣式控制 |
| 15 | 全局組件注冊 | component() | app.component('MyButton', Button) | 組件復(fù)用 |
| 16 | 自定義指令 | directive() | app.directive('highlight', { mounted: ... }) | 擴展能力 |
| 17 | nextTick() 的用途 | DOM 更新監(jiān)聽 | await nextTick() | 渲染流程控制 |
| 18 | 組件懶加載 | 異步組件 | defineAsyncComponent(() => import(...)) | 性能優(yōu)化 |
| 19 | 全局事件通信 | mitt | emitter.on('event', fn) | 跨組件通信 |
| 20 | v-model 的實現(xiàn) | 雙向綁定 | modelValue, update:modelValue | 表單組件設(shè)計 |
高頻考點補充
| 考點 | 描述 |
|---|---|
| Composition API | 替代 Options API,提升邏輯復(fù)用 |
| Reactivity API | ref, reactive, toRefs, watch, computed |
| Teleport / Portal | 渲染到任意 DOM 節(jié)點 |
| Fragment | 支持多個根節(jié)點 |
| TypeScript 支持 | 完整 TS 類型推導(dǎo) |
| Custom Renderer | 可定制渲染器(如 Canvas、SSR) |
| 性能優(yōu)化 | 更小的體積、更快的 Diff 算法 |
| 組合函數(shù)(Composable) | 封裝可復(fù)用邏輯 |
| Vue 3 的編譯器優(yōu)化 | Block Tree、Patch Flags |
| Vue 3 的生態(tài)支持 | Vite、Pinia、Vue Router 4、Element Plus |
到此這篇關(guān)于前端Vue3最常用的20道面試題總結(jié)的文章就介紹到這了,更多相關(guān)前端Vue3道面試題內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
antd-DatePicker組件獲取時間值,及相關(guān)設(shè)置方式
這篇文章主要介紹了antd-DatePicker組件獲取時間值,及相關(guān)設(shè)置方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
Vue利用axios發(fā)送請求并代理請求的實現(xiàn)代碼
在Web開發(fā)中,跨域問題是一個常見難題,通常由瀏覽器的同源策略引起,通過簡單配置vue.config.js文件,以及安裝axios依賴,即可實現(xiàn)前后端的無縫連接和數(shù)據(jù)交換,這種方法簡便有效,對于處理跨域請求問題非常實用2024-10-10

