【Vue3】前端Vue3最常用的 20 道面试题总结(含具体代码解析)

[复制链接]
发表于 2025-7-19 04:07:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
以下是老曹关于 Vue 3 最常用的 20 道面试题总结,涵盖 Vue 3 的焦点特性如 Composition API、相应式系统(ref / reactive)、生命周期钩子、组件通信、Teleport、Suspense、自界说指令等高频知识点。每道题都配有具体解释和代码示例,适实用于前端开发岗位的 Vue 3 技能面试准备,大家可以码住随时翻出来查阅背诵和练习!

1. Vue 3 和 Vue 2 的区别是什么?

问题: 解释 Vue 3 相比 Vue 2 的主要改进点。(最主要,不是全部,全部后续老曹会再扩展)
答案:
特性Vue 2Vue 3相应式系统Object.definePropertyProxy架构单一源码模块化架构(Tree-shakable)Composition API❌✅Fragment❌✅Suspense 组件❌✅自界说渲染器支持有限更灵活支持 TypeScript❌(需额外设置)✅ 原生支持
  1. // Vue 3 示例:使用 Composition API
  2. import { ref, onMounted } from 'vue';
  3. export default {
  4.   setup() {
  5.     const count = ref(0);
  6.     function increment() {
  7.       count.value++;
  8.     }
  9.     onMounted(() => {
  10.       console.log('组件挂载');
  11.     });
  12.     return { count, increment };
  13.   }
  14. };
复制代码

2. 如何在 Vue 3 中创建一个相应式对象?

问题: 使用 reactive() 创建一个相应式用户对象。
答案:
使用 reactive() 创建深层相应式对象。
  1. import { reactive } from 'vue';
  2. const user = reactive({
  3.   name: 'Alice',
  4.   age: 25
  5. });
复制代码

3. ref() 和 reactive() 的区别?

问题: 写出两者的不同点及实用场景。
答案:

  • ref():实用于基本类型或单个值。
  • reactive():实用于对象或复杂结构。
  1. import { ref, reactive } from 'vue';
  2. const count = ref(0); // 基本类型
  3. const user = reactive({ name: 'Bob' }); // 对象
  4. count.value++; // 必须用 .value
  5. user.name = 'Tom'; // 不需要 .value
复制代码

4. Vue 3 中如何监听数据变化?

问题: 使用 watchEffect 和 watch 的方式分别写出监听逻辑。
答案:

  • watchEffect:自动追踪依赖并实行副作用。
  • watch:手动指定监听的目的。
  1. import { ref, watchEffect, watch } from 'vue';
  2. const count = ref(0);
  3. // watchEffect
  4. watchEffect(() => {
  5.   console.log('Count changed:', count.value);
  6. });
  7. // watch
  8. watch(count, (newVal, oldVal) => {
  9.   console.log(`从 ${oldVal} 变为 ${newVal}`);
  10. });
复制代码

5. Vue 3 的生命周期钩子有哪些?如何使用?

问题: 在 setup() 中使用 onMounted 生命周期钩子。
答案:
Vue 3 提供了与 Vue 2 类似的生命周期钩子,但必须从 vue 导入使用。
  1. import { onMounted } from 'vue';
  2. export default {
  3.   setup() {
  4.     onMounted(() => {
  5.       console.log('组件已挂载');
  6.     });
  7.   }
  8. };
复制代码

6. Vue 3 中如何举行父子组件通信?

问题: 父组件向子组件转达数据,并触发事故。
答案:
使用 props接收父组件数据,使用 emit 触发事故。
  1. // 子组件 Child.vue
  2. export default {
  3.   props: ['title'],
  4.   emits: ['update'],
  5.   setup(props, { emit }) {
  6.     function handleClick() {
  7.       emit('update', 'New Value');
  8.     }
  9.     return { handleClick };
  10.   }
  11. };
  12. // 父组件 Parent.vue
  13. <template>
  14.   <Child :title="msg" @update="handleUpdate" />
  15. </template>
  16. <script>
  17. import Child from './Child.vue';
  18. export default {
  19.   components: { Child },
  20.   data() {
  21.     return {
  22.       msg: 'Hello'
  23.     };
  24.   },
  25.   methods: {
  26.     handleUpdate(value) {
  27.       console.log('收到更新:', value);
  28.     }
  29.   }
  30. };
  31. </script>
复制代码

7. Vue 3 的 setup() 函数的作用是什么?

问题: setup() 是什么?为什么它很重要?
答案:

  • setup() 是 Vue 3 Composition API 的入口函数。
  • 更换 Vue 2 中的 data、methods、computed 等选项。
  • 更好地组织逻辑复用和模块化代码。
  1. export default {
  2.   setup() {
  3.     const message = ref('Hello Vue 3');
  4.     function changeMessage() {
  5.       message.value = 'Updated!';
  6.     }
  7.     return { message, changeMessage };
  8.   }
  9. };
复制代码

8. Vue 3 中如何实现相应式计算属性?

问题: 使用 computed() 实现一个计算属性。
答案:
使用 computed() 创建相应式计算属性。
  1. import { ref, computed } from 'vue';
  2. export default {
  3.   setup() {
  4.     const firstName = ref('John');
  5.     const lastName = ref('Doe');
  6.     const fullName = computed(() => `${firstName.value} ${lastName.value}`);
  7.     return { firstName, lastName, fullName };
  8.   }
  9. };
复制代码

9. provide() 和 inject() 的作用是什么?

问题: 如何跨层级转达数据?
答案:
用于祖先组件向后代组件注入依赖,不通过 props 逐层转达。
  1. // 祖先组件
  2. import { provide, ref } from 'vue';
  3. export default {
  4.   setup() {
  5.     const theme = ref('dark');
  6.     provide('theme', theme);
  7.     return { theme };
  8.   }
  9. };
  10. // 后代组件
  11. import { inject } from 'vue';
  12. export default {
  13.   setup() {
  14.     const theme = inject('theme');
  15.     return { theme };
  16.   }
  17. };
复制代码

10. Vue 3 中如何使用插槽(Slot)?

问题: 实现一个默认插槽和具名插槽。
答案:
  1. <!-- 父组件 -->
  2. <template>
  3.   <Card>
  4.     <template #default>这是默认插槽内容</template>
  5.     <template #header>这是头部插槽</template>
  6.   </Card>
  7. </template>
  8. <!-- 子组件 Card.vue -->
  9. <template>
  10.   <div class="card">
  11.     <header><slot name="header"></slot></header>
  12.     <main><slot></slot></main>
  13.   </div>
  14. </template>
复制代码

11. Vue 3 中的 Teleport 有什么用途?

问题: 如何将模态框渲染到 <body> 下?
答案:
Teleport 可以将组件渲染到 DOM 中任意位置。
  1. <template>
  2.   <teleport to="body">
  3.     <div v-if="showModal" class="modal">这是一个模态框</div>
  4.   </teleport>
  5. </template>
复制代码

12. Vue 3 中的 Suspense 是什么?怎么用?

问题: 异步加载组件时显示加载状态。
答案:
Suspense 是一个内置组件,用于处置惩罚异步依赖。
  1. <template>
  2.   <suspense>
  3.     <template #default>
  4.       <AsyncComponent />
  5.     </template>
  6.     <template #fallback>
  7.       加载中...
  8.     </template>
  9.   </suspense>
  10. </template>
  11. <script>
  12. const AsyncComponent = defineAsyncComponent(() => import('./MyComponent.vue'));
  13. </script>
复制代码

13. Vue 3 中的 defineProps 和 defineEmits 是什么?

问题: 在 <script setup> 中如何声明 props 和 emits?
答案:
在 <script setup> 中直接使用 defineProps 和 defineEmits。
  1. <script setup>
  2. import { defineProps, defineEmits } from 'vue';
  3. const props = defineProps(['title']);
  4. const emit = defineEmits(['update']);
  5. function updateTitle() {
  6.   emit('update', 'New Title');
  7. }
  8. </script>
  9. <template>
  10.   <h1>{{ title }}</h1>
  11.   <button @click="updateTitle">更新标题</button>
  12. </template>
复制代码

14. Vue 3 中如何动态绑定样式?

问题: 动态设置背景颜色。
答案:
使用 :style 绑定对象。
  1. <template>
  2.   <div :style="{ backgroundColor: color }">{{ text }}</div>
  3. </template>
  4. <script>
  5. export default {
  6.   data() {
  7.     return {
  8.       color: 'lightblue',
  9.       text: '动态样式'
  10.     };
  11.   }
  12. };
  13. </script>
复制代码

15. Vue 3 中如何注册全局组件?

问题: 注册一个可全局使用的按钮组件。
答案:
  1. // main.js
  2. import { createApp } from 'vue';
  3. import App from './App.vue';
  4. import MyButton from './components/MyButton.vue';
  5. const app = createApp(App);
  6. app.component('MyButton', MyButton);
  7. app.mount('#app');
复制代码
  1. <!-- 使用 -->
  2. <template>
  3.   <my-button label="提交" />
  4. </template>
复制代码

16. Vue 3 中如何实现自界说指令?

问题: 实现一个高亮指令 v-highlight。
答案:
  1. // main.js
  2. import { createApp } from 'vue';
  3. import App from './App.vue';
  4. const app = createApp(App);
  5. app.directive('highlight', {
  6.   mounted(el) {
  7.     el.style.backgroundColor = '#f0e68c';
  8.   }
  9. });
  10. app.mount('#app');
复制代码
  1. <!-- 使用 -->
  2. <template>
  3.   <p v-highlight>这段文字被高亮了</p>
  4. </template>
复制代码

17. Vue 3 中的 nextTick() 怎么用?

问题: 修改 DOM 后等候更新完成。
答案:
使用 nextTick() 确保 DOM 更新完成后实行利用。
  1. import { nextTick } from 'vue';
  2. async function updateData() {
  3.   this.message = '更新后的内容';
  4.   await nextTick();
  5.   console.log('DOM 已更新');
  6. }
复制代码

18. Vue 3 中如何实现组件懒加载?

问题: 使用异步组件实现路由懒加载。
答案:
使用 defineAsyncComponent 实现懒加载。
  1. import { defineAsyncComponent } from 'vue';
  2. const AsyncComponent = defineAsyncComponent(() =>
  3.   import('./components/LazyComponent.vue')
  4. );
  5. export default {
  6.   components: {
  7.     AsyncComponent
  8.   }
  9. };
复制代码

19. Vue 3 中的 emitter 是什么?如何使用?

问题: 实现非父子组件之间的通信。
答案:
使用第三方库如 mitt 或 EventBus 实现全局通信。
  1. npm install mitt
复制代码
  1. // eventBus.js
  2. import mitt from 'mitt';
  3. export const emitter = mitt();
  4. // 发送事件
  5. import { emitter } from './eventBus';
  6. emitter.emit('update', 'Hello');
  7. // 接收事件
  8. import { emitter } from './eventBus';
  9. emitter.on('update', (msg) => {
  10.   console.log(msg);
  11. });
复制代码

20. Vue 3 中如何使用 v-model 实现双向绑定?

问题: 实现一个输入框组件的双向绑定。
答案:
使用 modelValue + update:modelValue。
  1. <template>
  2.   <input
  3.     :value="modelValue"
  4.     @input="$emit('update:modelValue', $event.target.value)"
  5.   />
  6. </template>
  7. <script>
  8. export default {
  9.   props: ['modelValue'],
  10.   emits: ['update:modelValue']
  11. };
  12. </script>
复制代码

📋 总结表格

编号标题形貌知识点示例代码常见考察点1Vue3 与 Vue2 的区别架构升级Proxy, Composition API框架明确2创建相应式对象reactive()reactive({})数据绑定3ref() vs reactive()相应式机制ref(0) vs reactive({})数据封装4数据监听watchEffect, watchwatch(count, () => {...})数据驱动5生命周期钩子onMounted, onUpdatedonMounted(() => {})组件控制6组件通信[props]/ emitdefineProps(['name'])组件设计7setup() 的作用Composition API 入口setup() { return {} }逻辑组织8计算属性computed()computed(() => a + b)相应式优化9跨级传参provide/injectprovide('theme', 'dark')数据共享10插槽使用默认插槽 / 具名插槽<slot name="header" />组件扩展11Teleport 的用途渲染到其他节点<teleport to="body">...</teleport>DOM 结构优化12Suspense 的用途异步加载<suspense><template #default>...异步组件13<script setup> 中的 [props]/ emit快捷方式defineProps(['title'])新语法糖14动态绑定样式:style:style="{ color: textColor }"样式控制15全局组件注册component()app.component('MyButton', Button)组件复用16自界说指令directive()app.directive('highlight', { mounted: ... })扩展本领17nextTick() 的用途DOM 更新监听await nextTick()渲染流程控制18组件懒加载异步组件defineAsyncComponent(() => import(...))性能优化19全局事故通信mittemitter.on('event', fn)跨组件通信20v-model 的实现双向绑定modelValue, update:modelValue表单组件设计
📌 高频考点补充

考点形貌Composition API更换 Options API,提升逻辑复用Reactivity APIref, reactive, toRefs, watch, computedTeleport / Portal渲染到任意 DOM 节点Fragment支持多个根节点TypeScript 支持完备 TS 类型推导Custom Renderer可定制渲染器(如 Canvas、SSR)性能优化更小的体积、更快的 Diff 算法组合函数(Composable)封装可复用逻辑Vue 3 的编译器优化Block Tree、Patch FlagsVue 3 的生态支持Vite、Pinia、Vue Router 4、Element Plus
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表