instructions

Record a Vue3 project construction process. Based on Vue 3.2.6 and VITe2.51, this paper uses UI library Element Plus, VUE-Router4, Layout Layout encapsulation, AXIOS request encapsulation, alias configuration, etc.

start

1.Install vue3 plug-ins using vscode development toolsVolarIn VUe2 we use Vetur.

  • Vue3 online code tool portal sfc.vuejs.org/

2.Execute initialization and installation commands:

NPM init vite You can enter the project name, choose the vue/ React project, and choose the JS/TS environment. Vue3 already supports TS. This article uses JS. NPM install Installs dependencies. Finally, execute NPM run dev to run the project.

Run the process if the error message shown above, can be performed manually node node_modules/esbuild/install. Js, and then execute NPM run dev

3.Install the vue – the router

Run NPM install vue-router@4. Vue3 versions of vuE-Router and vuex are 4.0. After the installation is complete, create SRC /router/index.js in the directory and write the following configuration:

import { createRouter, createWebHistory } from 'vue-router'
const routes = [
// ...
]

export default createRouter({
history: createWebHistory(),
routes,
})
Copy the code

Used in the main. Js

/ /... +
import router from './router/index'
createApp(App).use(router).mount('#app')
Copy the code

Vue – Router4 Hash mode createWebHashHistory History Mode createWebHistory. For details, see the official website.

4.Global style and SASS installation (alias is required to use @path, explained below)

Run NPM I sass -d and create SRC /styles/index.scss in the directory:

// @import './a.scss'; 
// Organize these style files as an exit while writing some global styles
Copy the code

Introduced in mian.js

import '@/styles/index.scss'
Copy the code

Tips: Vue3 style penetration uses ::deep(.className) or deep(.classname)

5.Element Plus is introduced on demand and globally

Install with NPM I element3 -s. If you can use most of the components, use global import as follows:

// main.js
import element3 from "element3";
import "element3/lib/theme-chalk/index.css";
createApp(App).use(router).use(element3).mount('#app')
Copy the code

If you only use a few components, you can load optimizations on demand by creating SRC /plugins/element3.js, as shown below

// Import plugins/element3.js as needed
import { ElButton, ElMenu, ElMenuItem } from 'element3'
import 'element3/lib/theme-chalk/button.css'
import 'element3/lib/theme-chalk/menu.css'
import 'element3/lib/theme-chalk/menu-item.css'
export default function (app{  
    app.use(ElButton) 
    app.use(ElMenu) 
    app.use(ElMenuItem)
}
// a reference in main.js
import element3 from '@/plugins/element3.js'
createApp(App).use(router).use(element3).mount('#app')
Copy the code

6.Layout create a file SRC/Layout /index.vue

// src/layout/index.vue<template> <! -- Top navigation --><Navbar /><! -- Page content section, routing exit --><AppMain /><! -- Bottom content --><Footer />
</template>

<script setup>
import Navbar from './Navbar.vue'
import AppMain from './AppMain.vue'
import Footer from './Footer.vue'
</script>
Copy the code

When using Layout, use layout. vue as the parent route. The route design is similar to the following:

// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/index.vue'
import Home from '@/views/home/Home.vue'
import Test from '@/views/test/Test.vue'
const routes = [
  {
    path: '/'.component: Layout,
    children: [{ path: ' '.component: Home }],
  },
  {
    path: '/test'.component: Layout,
    children: [{ path: ' '.component: Test }],
  },
]

export default createRouter({
  history: createWebHistory(),
  routes,
})
Copy the code

7.Axios requests encapsulation

Run the NPM I axios command to install axiOS

Create a new SRC /utils/request.js file and wrap axios in it

import axios from 'axios'
// You can import an Element Plus popup instead of an alert for interaction

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASEURL, // Use the set global environment
  timeout: 30 * 1000.// request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) = > {
    // Add the token and other logic
    // config.headers["Authorization"] = getToken();
    return config
  },
  (error) = > {
    console.log(error)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) = > {
    const res = response.data // Handle according to the interface return parameters

    if(res.code ! = =200) {
      if (res.code === 50000) {
        // Process according to the status code
        alert('An internal server exception occurred. Please try again later.')}return Promise.reject(new Error(res.msg || 'Error'))}else {
      // The call returned data successfully
      return Promise.resolve(res)
    }
  },
  (error) = > {
    console.log('err' + error) // Handle the exception
    return Promise.reject(error)
  }
)

export default service
Copy the code

Create SRC/API directory, you can create a JS file for each module or page, convenient management and maintenance API. In this example, create a SRC/API /home.js file and write the code

// Import the wrapped request.js
import request from '@/utils/request'

export function getList(query) {
  return request({
    url: '/list'.method: 'get'.params: query,
  })
}
Copy the code

Used in home.vue

<script setup>
import { getList } from '@/api/home.js'
const query = { pagenum: 1 }
getList(query)
  .then((res) = > {
    console.log(res) // Call successfully returned data
  })
  .error((err) = > {
    console.log(err) // Call the logic to execute for failure
  })
</script>
Copy the code

8.Correlation of environment variables

Env.production production environment.env.development development environment.env.staging test environment. Add the following code to each of the three files in the project root directory: env.production production environment.env.staging test environment

# .env.production
VITE_APP_BASEURL=https://www.prod.api/
Copy the code
# .env.development
VITE_APP_BASEURL=https://www.test.api/
Copy the code
# .env.staging
VITE_APP_BASEURL=https://www.test.api/
Copy the code

Use:

console.log(import.meta.env.VITE_APP_BASEURL)
// The console outputs different URL paths under different compilation environments
Copy the code

Override the default mode used by the command by passing the –mode option flag in package.json

  "scripts": {
    "dev": "vite"."build:stage": "vite build --mode staging"."build:prod": "vite build --mode production"."serve": "vite preview"
  },
Copy the code

Thus, the production environment packages NPM Run Build :prod and the test/pre-release environment packages NPM Run Build :stage

9.Alias configuration in vite

Add code to the vite. Config. js file in the root directory

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: [{ find: The '@'.replacement: resolve(__dirname, 'src')}],},base: '/',})Copy the code

See the official website for more configuration items