Vue3 项目初始化搭建

197 阅读3分钟

「这是我参与2022首次更文挑战的第2天,活动详情查看:2022首次更文挑战

前言

技术栈使用了 Vue3 + Vite + Sass + ElementUI + ESLint

项目搭建

创建

我们直接使用Vite 来快速构建 Vue 项目

npm init @vitejs/app vue3-node

然后选择Vue框架。
安装 elementUI 作为组件库

npm install element-plus --save

在main.js 中注册

import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css'
const app = createApp(App);

app.use(ElementPlus);
app.mount('#app')

为了方便使用,在vite.config.js配置文件中增加别名@,后续有需要可以在这边添加。

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path';

// https://vitejs.dev/config/
export default defineConfig({
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  },
  plugins: [vue()]
})

接入路由

在src目录下创建router文件夹,文件夹里面创建路由信息index.js

import { createRouter, createWebHashHistory} from 'vue-router'

const routes = [
  {
    path: '/',
    component: () => import( /* webpackChunkName: "Home" */  '../views/home.vue')
  }
]

const router = createRouter({
  // 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
  history: createWebHashHistory(),
  routes, // `routes: routes` 的缩写
})
export default router;

main.js里进行注册

import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import router from './router'
const app = createApp(App);

app.use(router)
app.use(ElementPlus);
app.mount('#app')

修改App.vue

<template>
  <router-view></router-view>
</template>

接入 Vuex

安装

npm install vuex@next --save

创建 src/store/index.js 文件

import { createStore } from 'vuex'

const defaultState = {
  count: 0
}

// Create a new store instance.
export default createStore({
  state() {
    return defaultState
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  actions: {
    increment(context) {
      context.commit('increment')
    }
  },
  getters: {
    double(state) {
      return 2 * state.count
    }
  }
})

在 main.js 文件中挂载 Vuex 配置

import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import router from './router'
import store from './store/index'
const app = createApp(App);

app.use(store)
app.use(router)
app.use(ElementPlus);
app.mount('#app')

接入Axios

使用Axios 来作为http请求的库,为了方便使用,我们做一些封装,在src目录下创建api目录,目录下有个index.js 文件

// src/api/index.js
import axios from 'axios';
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, // api 的 base_url
  timeout: 50000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json'
  },
  transformRequest: [data => JSON.stringify(data)] // 参数转换
});

// axios实例拦截响应
service.interceptors.response.use(
  (response) => {
    if (response.status !== 200) {
      ElMessage.error('网络连接异常,请稍后再试!');
    }
    return response;
  },
  // 请求失败
  (error) => {
    ElMessage.error(error.message);
  }
);

// axios实例拦截请求
service.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
) 

export default service;

我们上面使用了import.meta.env.VITE_BASE_API 来获取环境变量VITE_BASE_API,所以需要在根目录创建.env文件,进行设置环境变量

VITE_BASE_API=http://localhost:3000

然后在api目录下在创建一个api文件,这个文件的作用是用来保存请求接口的方法,后续使用时,在这个文件新增接口请求的方法,然后在具体页面调用,这样的好处是,多个地方调用同一个接口时方便使用和修改。比如我们现在需要请求一个接口 /api/hello

// src/api/api.js
import request  from './index';

export function getHello(params) {
  return request({
    url: '/api/hello',
    method: 'get',
    params
  });
}

需要使用的话,我们在使用的页面进行引入

// views/home.vue
<template>
  <div>Home</div>
</template>

<script>
import { onMounted } from 'vue'
import { getHello }from '@/api/api'
export default {
   setup () {
     onMounted(() => {
       getHello().then(res=> {
         console.log(res);
       }).catch(err=>{
         console.log(err);
       })
     })
   }
}
</script>

集成 Sass

npm i sass -D

使用

...
<style lang="scss" scoped>

</style>

加入ESLint

ESLint 是一个可以检查代码质量和风格问题,并且支持部分问题自动修复。如果一个项目有多个成员,可能会因为各自的编码水平或编码风格不同,导致代码质量问题,所以我们需要加入ESLint 来解决。

安装

npm i eslint -D

安装完成后执行 npx eslint --init 进行初始化,按照提示进行操作。
首先选择To check syntax, find problems, and enforce code style(检查语法、发现问题并强制执行代码风格)
然后选择JavaScript modules (import/export) 和选择 Vue.js 不使用Ts,选择运行的环境是浏览器还是Node,最后选择预设的风格指南 Airbnb ,后面我们也可以自己进行自定义规则。

配置 ESLint

打开配置文件.eslintrc.js

module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'plugin:vue/essential',
    'airbnb-base',
  ],
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  plugins: [
    'vue',
  ],
  rules: {
    'no-console': 'off',
    'import/extensions': 'off',
    'import/no-unresolved': 'off',
    'no-plusplus': 'off',
    'no-param-reassign': 'off',
    'vue/no-multiple-template-root': 'off',
  },
};

在这个文件里可以加入自己团队习惯的规则

结束

到这里我们就完成了Vue3 初始化的架构。