《前后端面試題
》專欄集合了前后端各個知識模塊的面試題,包括html,javascript,css,vue,react,java,Openlayers,leaflet,cesium,mapboxGL,threejs,nodejs,mangoDB,MySQL,Linux… 。
文章目錄
- 一、本文面試題目錄
- 31. Vue 3中如何實現表單雙向綁定?
- 32. Vue 3的響應式系統相比Vue 2有哪些性能提升?
- 33. Vue 3中如何實現路由懶加載?
- 34. Vue 3中如何處理異步操作?
- 35. Vue 3中如何進行單元測試?
- 36. Vue 3中如何使用Vuex?
- 37. Vue 3中如何實現插件?
- 38. Vue 3中如何使用自定義過濾器?
- 39. Vue 3中如何實現服務端渲染(SSR)?
- 40. Vue 3中如何優化大型應用的性能?
- 41. Vue 3中如何實現國際化(i18n)?
- 42. Vue 3中如何處理錯誤邊界?
- 43. Vue 3中如何實現組件通信?
- 44. Vue 3中如何使用v-memo優化渲染性能?
- 45. Vue 3中如何使用VueUse?
- 二、120道面試題目錄列表
一、本文面試題目錄
31. Vue 3中如何實現表單雙向綁定?
在Vue 3中,可以使用v-model
指令實現表單雙向綁定。對于基礎組件,它是v-bind
和v-on
的語法糖。例如:
<template><input v-model="message" type="text" /><p>{{ message }}</p>
</template><script setup>
import { ref } from 'vue';
const message = ref('');
</script>
對于自定義組件,需要通過modelValue
prop和update:modelValue
事件實現:
<!-- 父組件 -->
<template><CustomInput v-model="message" />
</template><!-- 子組件 -->
<template><input :value="modelValue" @input="emit('update:modelValue', $event.target.value)" />
</template><script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({modelValue: String
});
const emits = defineEmits(['update:modelValue']);
</script>
32. Vue 3的響應式系統相比Vue 2有哪些性能提升?
Vue 3的響應式系統使用Proxy替代Object.defineProperty,帶來以下性能提升:
- 深度監聽優化:Proxy可以攔截對象的所有操作,無需遞歸遍歷所有屬性。
- 動態屬性支持:可以檢測到對象屬性的添加和刪除,無需使用
Vue.set
/Vue.delete
。 - 更好的數組支持:可以攔截數組的原生方法,如
push
、pop
等。 - 懶處理:只有在訪問嵌套屬性時才會創建響應式代理,減少初始開銷。
33. Vue 3中如何實現路由懶加載?
Vue 3中推薦使用動態導入實現路由懶加載:
import { createRouter, createWebHistory } from 'vue-router';const routes = [{path: '/home',name: 'Home',component: () => import('../views/Home.vue') // 懶加載組件},{path: '/about',name: 'About',component: () => import('../views/About.vue') // 懶加載組件}
];const router = createRouter({history: createWebHistory(),routes
});export default router;
34. Vue 3中如何處理異步操作?
Vue 3中處理異步操作的方式有:
- async/await:在setup函數或生命周期鉤子中使用async/await。
<script setup>
import { onMounted } from 'vue';onMounted(async () => {const data = await fetchData();console.log(data);
});
</script>
- Suspense組件:處理異步組件加載狀態。
<template><Suspense><template #default><AsyncComponent /></template><template #fallback><div>Loading...</div></template></Suspense>
</template>
- 自定義組合式函數:封裝異步邏輯。
// useFetch.js
import { ref, onMounted } from 'vue';export function useFetch(url) {const data = ref(null);const error = ref(null);const loading = ref(true);const fetchData = async () => {try {const response = await fetch(url);data.value = await response.json();} catch (err) {error.value = err;} finally {loading.value = false;}};onMounted(fetchData);return { data, error, loading };
}
35. Vue 3中如何進行單元測試?
Vue 3的單元測試可以使用以下工具和方法:
- @vue/test-utils:Vue官方測試工具庫。
- Jest:JavaScript測試框架。
- Vitest:Vite原生的測試框架,速度更快。
示例測試代碼:
import { describe, it, expect } from 'vitest';
import { shallowMount } from '@vue/test-utils';
import HelloWorld from './HelloWorld.vue';describe('HelloWorld.vue', () => {it('renders props.msg when passed', () => {const msg = 'new message';const wrapper = shallowMount(HelloWorld, {props: { msg }});expect(wrapper.text()).toContain(msg);});
});
36. Vue 3中如何使用Vuex?
Vue 3中使用Vuex 4,需要創建store并通過createStore
函數初始化:
// store/index.js
import { createStore } from 'vuex';const store = createStore({state() {return {count: 0};},mutations: {increment(state) {state.count++;}},actions: {incrementAsync({ commit }) {setTimeout(() => {commit('increment');}, 1000);}},getters: {doubleCount(state) {return state.count * 2;}}
});export default store;
在main.js中安裝store:
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';const app = createApp(App);
app.use(store);
app.mount('#app');
37. Vue 3中如何實現插件?
Vue 3中實現插件需要定義一個包含install
方法的對象:
// plugins/myPlugin.js
export const myPlugin = {install(app, options) {// 全局注冊組件app.component('MyComponent', {template: '<div>Global Component</div>'});// 全局添加方法app.config.globalProperties.$myMethod = () => {console.log('This is a global method');};// 注入provideapp.provide('myPlugin', options);}
};
在main.js中使用插件:
import { createApp } from 'vue';
import App from './App.vue';
import { myPlugin } from './plugins/myPlugin';const app = createApp(App);
app.use(myPlugin, { option: 'value' });
app.mount('#app');
38. Vue 3中如何使用自定義過濾器?
Vue 3中移除了過濾器,推薦使用計算屬性或方法替代:
// 計算屬性替代
<script setup>
import { computed, ref } from 'vue';const price = ref(100);
const formattedPrice = computed(() => {return `$${price.value.toFixed(2)}`;
});
</script><template><div>{{ formattedPrice }}</div>
</template>
或使用全局方法:
// main.js
app.config.globalProperties.$formatPrice = (price) => {return `$${price.toFixed(2)}`;
};// 模板中使用
<template><div>{{ $formatPrice(price) }}</div>
</template>
39. Vue 3中如何實現服務端渲染(SSR)?
Vue 3的SSR可以通過以下方式實現:
- Vue CLI + @vue/server-renderer:手動配置SSR環境。
- Nuxt 3:官方推薦的Vue 3 SSR框架。
- Vite + createSSRApp:使用Vite的SSR支持。
基本步驟:
- 創建Vue應用實例:
// src/main.js
import { createSSRApp } from 'vue';
import App from './App.vue';export function createApp() {const app = createSSRApp(App);return { app };
}
- 服務端渲染邏輯:
// server.js
import { createApp } from './src/main.js';
import { renderToString } from '@vue/server-renderer';server.get('*', async (req, res) => {const { app } = createApp();const html = await renderToString(app);res.send(`<!DOCTYPE html><html><head><title>Vue 3 SSR</title></head><body><div id="app">${html}</div><script src="/client.js"></script></body></html>`);
});
40. Vue 3中如何優化大型應用的性能?
優化Vue 3大型應用性能的方法:
- 路由懶加載:將路由組件分割成多個小文件,按需加載。
- 組件懶加載:使用
defineAsyncComponent
動態加載非關鍵組件。 - 虛擬列表:處理大量數據渲染時,只渲染可視區域的內容。
- Tree Shaking:利用Vite/Webpack的Tree Shaking功能,移除未使用的代碼。
- 緩存組件:使用
keep-alive
緩存頻繁切換的組件。 - 減少響應式對象大小:避免將大型對象或數組定義為響應式數據。
- 使用v-memo/v-bind:once:減少不必要的重新渲染。
No. | 大劍師精品GIS教程推薦 |
---|---|
0 | 地圖渲染基礎- 【WebGL 教程】 - 【Canvas 教程】 - 【SVG 教程】 |
1 | Openlayers 【入門教程】 - 【源代碼+示例 300+】 |
2 | Leaflet 【入門教程】 - 【源代碼+圖文示例 150+】 |
3 | MapboxGL 【入門教程】 - 【源代碼+圖文示例150+】 |
4 | Cesium 【入門教程】 - 【源代碼+綜合教程 200+】 |
5 | threejs 【中文API】 - 【源代碼+圖文示例200+】 |
41. Vue 3中如何實現國際化(i18n)?
Vue 3中實現國際化可以使用vue-i18n
v9+:
// i18n.js
import { createI18n } from 'vue-i18n';const messages = {en: {message: {hello: 'Hello World'}},zh: {message: {hello: '你好,世界'}}
};const i18n = createI18n({locale: 'en', // 默認語言messages
});export default i18n;
在main.js中安裝:
import { createApp } from 'vue';
import App from './App.vue';
import i18n from './i18n';const app = createApp(App);
app.use(i18n);
app.mount('#app');
在模板中使用:
<template><div>{{ $t('message.hello') }}</div>
</template>
42. Vue 3中如何處理錯誤邊界?
Vue 3中可以使用app.config.errorHandler
全局捕獲錯誤:
// main.js
const app = createApp(App);app.config.errorHandler = (err, instance, info) => {// 記錄錯誤信息console.error('Error:', err);console.error('Component instance:', instance);console.error('Error info:', info);// 可以在這里顯示錯誤提示組件
};app.mount('#app');
也可以在組件中使用onErrorCaptured
生命周期鉤子捕獲子組件錯誤:
<script setup>
import { onErrorCaptured } from 'vue';onErrorCaptured((err, instance, info) => {// 處理錯誤console.log('Error captured:', err);// 返回false阻止錯誤繼續向上傳播return false;
});
</script>
43. Vue 3中如何實現組件通信?
Vue 3中實現組件通信的方式有:
- props和$emit:父子組件通信的基本方式。
- 事件總線:創建全局事件總線,用于跨組件通信。
- provide/inject:跨層級組件通信。
- Vuex/Pinia:狀態管理庫,用于全局狀態共享。
- 自定義事件:使用
EventEmitter
實現自定義事件系統。 - Composition API:通過組合式函數共享邏輯和狀態。
44. Vue 3中如何使用v-memo優化渲染性能?
v-memo
是Vue 3新增的指令,用于緩存渲染結果,避免不必要的重新渲染:
<!-- 僅當item.id或item.name變化時才重新渲染 -->
<div v-for="item in list" v-memo="[item.id, item.name]">{{ item.name }}
</div>
注意:
v-memo
需要傳入一個依賴數組。- 僅在性能敏感的場景使用,避免過度使用。
- 不要在依賴數組中包含復雜對象,應使用原始值。
45. Vue 3中如何使用VueUse?
VueUse是一個基于Vue 3 Composition API的實用函數集合。使用步驟:
- 安裝:
npm install @vueuse/core
- 在組件中導入使用:
<script setup>
import { useMouse, useIntersectionObserver } from '@vueuse/core';// 使用鼠標位置
const { x, y } = useMouse();// 使用Intersection Observer
const target = ref(null);
const { isIntersecting } = useIntersectionObserver(target, {threshold: 0.5
});
</script><template><div ref="target">Mouse position: {{ x }}, {{ y }}<div v-if="isIntersecting">元素可見</div></div>
</template>
二、120道面試題目錄列表
文章序號 | vue3面試題120道 |
---|---|
1 | vue3 面試題及詳細答案(01 - 15) |
2 | vue3 面試題及詳細答案(16 - 30) |
3 | vue3 面試題及詳細答案(31 - 45) |
4 | vue3 面試題及詳細答案(46 - 60) |
5 | vue3 面試題及詳細答案(61 - 75) |
6 | vue3 面試題及詳細答案(76 - 90) |
7 | vue3 面試題及詳細答案(91 - 105) |
8 | vue3 面試題及詳細答案(106 - 120) |