bashnpm install -g @vue/cli# 或使用 yarnyarn global add @vue/cli
由于 Vue CLI 4+ 默认使用 Vue 3,需通过以下方式创建 Vue 2 项目:
bashvue create my-project
在提示中选择 Manually select features
,然后勾选以下配置:
markdown◉ Babel◉ Router ◉ Vuex ◉ CSS Pre-processors ◉ Linter / Formatter
选择 Vue 2
版本。
其他配置按需选择(如 ESLint 规则、CSS 预处理器等)。
vue.config.js
在项目根目录创建 vue.config.js
,常用配置如下:
javascriptmodule.exports = { publicPath: process.env.NODE_ENV === 'production' ? '/my-project/' : '/', // 部署路径 outputDir: 'dist', // 打包输出目录 assetsDir: 'static', // 静态资源目录 lintOnSave: process.env.NODE_ENV !== 'production', // 生产环境禁用 ESLint devServer: { port: 8080, // 开发服务器端口 proxy: { '/api': { target: 'http://api.example.com', // 代理目标地址 changeOrigin: true, pathRewrite: { '^/api': '' } } } }, configureWebpack: { resolve: { alias: { '@': path.resolve(__dirname, 'src') // 配置路径别名 } } }};
bashnpm install axios sass sass-loader element-ui --save# 或使用 yarnyarn add axios sass sass-loader element-ui
在 src/main.js
中添加:
javascriptimport ElementUI from 'element-ui';import 'element-ui/lib/theme-chalk/index.css';Vue.use(ElementUI);
src/router/index.js
)javascriptimport Vue from 'vue';import VueRouter from 'vue-router';import Home from '@/views/Home.vue';Vue.use(VueRouter);const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', component: () => import('@/views/About.vue') }];const router = new VueRouter({ mode: 'history', // 使用 HTML5 History 模式 base: process.env.BASE_URL, routes});export default router;
src/store/index.js
)javascriptimport Vue from 'vue';import Vuex from 'vuex';Vue.use(Vuex);export default new Vuex.Store({ state: { count: 0 }, mutations: { increment(state) { state.count++; } }, actions: { incrementAsync({ commit }) { setTimeout(() => commit('increment'), 1000); } }});
markdown├── public # 静态资源(直接复制到输出目录)├── src │ ├── assets # 静态资源(如图片、字体) │ ├── components # 公共组件 │ ├── views # 页面级组件 │ ├── router # 路由配置 │ ├── store # Vuex 状态管理 │ └── main.js # 入口文件 ├── .eslintrc.js # ESLint 配置 ├── babel.config.js # Babel 配置 └── package.json # 依赖管理
bashnpm run serve # 启动开发服务器npm run build # 生产环境打包npm run lint # 代码格式检查和修复
兼容性:在 babel.config.js
或 package.json
中配置 browserslist
,确保代码兼容目标浏览器。
环境变量:在项目根目录创建 .env.development
和 .env.production
定义环境变量(前缀 VUE_APP_
)。
代码规范:在 .eslintrc.js
中自定义 ESLint 规则,或使用 prettier
统一代码风格。
通过以上步骤,即可完成 Vue 2 项目的创建和基础配置。
期待继续分享