《前后端面試題
》專欄集合了前后端各個知識模塊的面試題,包括html,javascript,css,vue,react,java,Openlayers,leaflet,cesium,mapboxGL,threejs,nodejs,mangoDB,MySQL,Linux… 。
文章目錄
- 一、本文面試題目錄
- 141. Vue2中如何優化大型應用的構建體積?
- 142. Vue2中如何實現動態修改CSS變量?
- 143. Vue2中如何處理異步組件加載失敗的情況?
- 144. Vue2中如何實現服務端渲染(SSR)的路由預取?
- 145. Vue2中如何實現組件的拖拽排序?
- 146. Vue2中如何實現自定義構建流程?
- 147. Vue2中如何實現事件節流與防抖?
- 148. Vue2中如何實現組件的懶加載與預加載?
- 149. Vue2中如何實現Vuex的模塊化?
- 150. Vue2中如何實現微前端架構?
- 二、150道面試題目錄列表
一、本文面試題目錄
141. Vue2中如何優化大型應用的構建體積?
答案:
Vue2中優化構建體積的方法包括:
- 按需加載組件:使用動態導入(
() => import('組件路徑')
)實現路由懶加載或組件懶加載。 - Tree Shaking:確保使用ES6模塊語法,配合Webpack或Rollup移除未使用的代碼。
- 壓縮代碼:使用
terser-webpack-plugin
壓縮JS,css-minimizer-webpack-plugin
壓縮CSS。 - 分割第三方庫:通過
optimization.splitChunks
將Vue、axios等庫單獨打包。 - 移除生產環境警告:在
vue.config.js
中配置productionSourceMap: false
。 - 使用CDN引入外部資源:在HTML中通過CDN加載Vue、Element UI等庫,減少打包體積。
示例配置(vue.config.js
):
module.exports = {configureWebpack: {optimization: {splitChunks: {chunks: 'all',},},},productionSourceMap: false,
};
142. Vue2中如何實現動態修改CSS變量?
答案:
Vue2中可通過JavaScript動態修改CSS變量,步驟如下:
- 在CSS中定義變量:
:root {--primary-color: #3498db; }
- 在Vue組件中修改變量:
export default {methods: {changeTheme() {document.documentElement.style.setProperty('--primary-color', '#e74c3c');},}, };
- 結合Vuex管理主題狀態:
// store.js export default {state: { theme: 'light' },mutations: {SET_THEME(state, theme) {state.theme = theme;const root = document.documentElement;if (theme === 'dark') {root.style.setProperty('--primary-color', '#333');} else {root.style.setProperty('--primary-color', '#3498db');}},}, };
143. Vue2中如何處理異步組件加載失敗的情況?
答案:
Vue2中處理異步組件加載失敗的方法如下:
- 使用Error Boundary組件:
const AsyncComponent = () =>import('./AsyncComponent.vue').catch(error => {// 處理加載失敗,如顯示錯誤組件console.error('組件加載失敗:', error);return import('./ErrorComponent.vue');});
- 全局錯誤捕獲:
Vue.config.errorHandler = (err, vm, info) => {if (info.includes('async')) {console.error('異步組件加載失敗:', err);} };
- 在模板中使用條件渲染:
<template><div><AsyncComponent v-if="!hasError" /><ErrorComponent v-else /></div> </template><script> export default {data() {return { hasError: false };},components: {AsyncComponent: () =>import('./AsyncComponent.vue').catch(() => {this.hasError = true;}),}, }; </script>
144. Vue2中如何實現服務端渲染(SSR)的路由預取?
答案:
Vue2的SSR中實現路由預取的步驟如下:
- 在路由組件中定義
asyncData
方法:export default {asyncData({ store, route }) {return store.dispatch('fetchPost', route.params.id);}, };
- 在服務端渲染時調用
asyncData
:// server-entry.js router.onReady(() => {const matchedComponents = router.getMatchedComponents();if (!matchedComponents.length) {return reject({ code: 404 });}return Promise.all(matchedComponents.map(component => {if (component.asyncData) {return component.asyncData({store,route: router.currentRoute,});}})).then(() => {context.state = store.state;resolve(app);}); });
- 在客戶端激活時復用服務端數據:
// client-entry.js if (window.__INITIAL_STATE__) {store.replaceState(window.__INITIAL_STATE__); }
145. Vue2中如何實現組件的拖拽排序?
答案:
Vue2中實現拖拽排序可使用vuedraggable
庫,步驟如下:
- 安裝依賴:
npm install vuedraggable
- 在組件中使用:
<template><draggable v-model="list" @end="onDragEnd"><div v-for="item in list" :key="item.id">{{ item.name }}</div></draggable> </template><script> import draggable from 'vuedraggable';export default {components: { draggable },data() {return {list: [{ id: 1, name: 'Item 1' },{ id: 2, name: 'Item 2' },],};},methods: {onDragEnd(event) {console.log('排序變化:', event);// 更新數據或提交到后端},}, }; </script>
- 樣式定制:
.draggable-item {cursor: move;transition: all 0.2s; } .draggable-item.dragging {opacity: 0.5;background-color: #f5f5f5; }
146. Vue2中如何實現自定義構建流程?
答案:
Vue2中自定義構建流程可通過vue.config.js
配置,常見場景包括:
- 修改Webpack配置:
// vue.config.js module.exports = {configureWebpack: {resolve: {alias: {'@': path.resolve(__dirname, 'src'),},},},chainWebpack: config => {// 修改圖片加載器config.module.rule('images').use('url-loader').loader('url-loader').tap(options => {options.limit = 10000;return options;});}, };
- 添加自定義插件:
const MyPlugin = require('./my-plugin');module.exports = {configureWebpack: {plugins: [new MyPlugin()],}, };
- 多環境配置:
# package.json {"scripts": {"build:prod": "vue-cli-service build --mode production","build:test": "vue-cli-service build --mode test"} }
147. Vue2中如何實現事件節流與防抖?
答案:
Vue2中實現事件節流與防抖的方法如下:
- 手動實現防抖:
export default {methods: {debounce(fn, delay) {let timer;return function(...args) {clearTimeout(timer);timer = setTimeout(() => {fn.apply(this, args);}, delay);};},handleSearch: function() {// 使用防抖處理搜索}.debounce(300), // 300ms防抖}, };
- 使用lodash庫:
npm install lodash
import { debounce, throttle } from 'lodash';export default {created() {// 防抖this.debouncedSearch = debounce(this.search, 300);// 節流this.throttledScroll = throttle(this.handleScroll, 200);},methods: {search() { /* 搜索邏輯 */ },handleScroll() { /* 滾動邏輯 */ }} };
- 自定義指令:
Vue.directive('debounce', {inserted(el, binding) {let timer;el.addEventListener('click', () => {if (timer) clearTimeout(timer);timer = setTimeout(() => {binding.value();}, 300);});}, });
148. Vue2中如何實現組件的懶加載與預加載?
答案:
Vue2中實現組件懶加載與預加載的方法如下:
- 懶加載(按需加載):
// 路由配置 {path: '/about',component: () => import('./views/About.vue'), // 懶加載 }
- 預加載(Prefetch):
// 路由配置 {path: '/contact',component: () => import(/* webpackPrefetch: true */ './views/Contact.vue'), }
- 條件預加載:
// 在特定條件下預加載組件 if (shouldPrefetch) {import('./HeavyComponent.vue'); }
- 自定義預加載策略:
// 在組件掛載后預加載其他組件 export default {mounted() {// 當用戶停留在當前頁面時預加載下一個可能訪問的頁面this.$nextTick(() => {import('./NextPage.vue');});}, };
149. Vue2中如何實現Vuex的模塊化?
答案:
Vue2中實現Vuex模塊化的方法如下:
- 使用modules選項分割store:
// store/index.js import Vue from 'vue'; import Vuex from 'vuex'; import user from './modules/user'; import cart from './modules/cart';Vue.use(Vuex);export default new Vuex.Store({modules: {user,cart,}, });
- 模塊文件示例:
// store/modules/user.js export default {namespaced: true, // 啟用命名空間state: {userInfo: null,},mutations: {SET_USER(state, user) {state.userInfo = user;},},actions: {login({ commit }, credentials) {// 登錄邏輯commit('SET_USER', credentials);},},getters: {isLoggedIn: state => !!state.userInfo,}, };
- 在組件中使用命名空間模塊:
import { mapState, mapActions } from 'vuex';export default {computed: {...mapState('user', ['userInfo', 'isLoggedIn']),},methods: {...mapActions('user', ['login']),}, };
150. Vue2中如何實現微前端架構?
答案:
Vue2中實現微前端架構的常見方案如下:
- 使用iframe:
<iframe src="https://子應用地址" frameborder="0"></iframe>
- 使用single-spa框架:
// 主應用配置 import singleSpaVue from 'single-spa-vue'; import Vue from 'vue'; import App from './App.vue';const vueLifecycles = singleSpaVue({Vue,appOptions: {render: h => h(App),}, });export const bootstrap = vueLifecycles.bootstrap; export const mount = vueLifecycles.mount; export const unmount = vueLifecycles.unmount;
- 使用qiankun框架:
// 主應用注冊子應用 import { registerMicroApps, start } from 'qiankun';registerMicroApps([{name: 'app1',entry: '//localhost:8081',container: '#sub-app-container',activeRule: '/app1',}, ]);start();
- 使用Web Components:
// 將Vue組件封裝為Web Component import { defineCustomElement } from 'vue'; import MyComponent from './MyComponent.vue';const MyVueElement = defineCustomElement(MyComponent);customElements.define('my-vue-element', MyVueElement);
- 使用組合式集成:
在主應用中通過路由加載子應用的入口組件,子應用保持獨立構建。
二、150道面試題目錄列表
文章序號 | vue2面試題150道 |
---|---|
1 | vue2 面試題及詳細答案(01 - 20) |
2 | vue2 面試題及詳細答案(21 - 40) |
3 | vue2 面試題及詳細答案(41 - 60) |
4 | vue2 面試題及詳細答案(61 - 70) |
5 | vue2 面試題及詳細答案(71 - 80) |
6 | vue2 面試題及詳細答案(81 - 90) |
7 | vue2 面試題及詳細答案(91 - 100) |
8 | vue2 面試題及詳細答案(101 - 120) |
9 | vue2 面試題及詳細答案(121 - 130) |
10 | vue2 面試題及詳細答案(131 - 140) |
11 | vue2 面試題及詳細答案(141 - 150) |