《前后端面试题
》专栏集合了前后端各个知识模块的面试题,包括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) |