introduce

This paper mainly introduces the construction of vite + VUe3 + VuE-Router4 + vuex4 + Ant-Design-vue2 + AXIos + MockJS project. In 2021, if you haven’t experienced the speed of vite, you should try it.

Create a Vite project

Executing the create command

Execute the Vite project creation command. During the creation navigation, select vue+ TS mode.

yarn create vite
yarn
yarn dev
Copy the code

Modify the Vite configuration file

When you run vite from the command line, vite automatically parses the file named vite.config.js in the project root directory. Here, let’s briefly set the @ to SRC and the proxy proxy that must be set up for development and back-end mediation. For other parameters, see the official website. (cn. Vitejs. Dev/config /)

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path' // The path module cannot be found. Yarn add @types/node --dev is available

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      The '@': resolve(__dirname, 'src') // Set '@' to point to 'SRC'}},server: {
    port: 3000.// Set the service startup port number
    open: true.// Set whether the browser opens automatically when the service starts
    / / agent
    proxy: {
      '/api': {
        target: 'http://API Gateway domain name '.changeOrigin: true.rewrite: (path) = > path.replace(/^\/api/.' ')},}}})Copy the code

Install the vue – the router

Executing installation Commands

yarn add vue-router@4
Copy the code

Creating a Router file

Create the SRC /router/index.ts file and use lazy route loading to optimize the access performance.

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/'.name: 'home'.component: () = > import('@/views/Home.vue') // Lazy route loading is recommended to optimize access performance
  },
  {
    path: '/demo'.name: 'demo'.component: () = > import('@/views/Demo.vue')}]const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router
Copy the code

The introduction of the router

Use router in the vue example in main.ts file

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'

createApp(App).use(router).mount('#app')
Copy the code

Use the router-view component

Using the router-view component in the app.vue file, the router-view component is used to render the route matching component.

<template>
  <router-view />
</template>
Copy the code

Install vuex

Executing installation Commands

yarn add vuex@next
Copy the code

Create store file

Create the SRC /store/index.ts file

import { createStore } from 'vuex'

const defaultState = {
  count: 0
}
const store = createStore({
  state () {
    return {
      count: 0}},mutations: {
    increment (state: typeof defaultState) {
      state.count++
    }
  }
})
export default store;
Copy the code

The introduction of vuex

Use store in the vue example in the main.ts file so that we can use the global state management plug-in vuex in page coding.

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
import store from './store/index'

createApp(App).use(router).use(store).mount('#app')
Copy the code

Install the UI library Ant-Design-vue

Executing installation Commands

yarn add ant-design-vue@next
Copy the code

Reference ant – design – vue

Introduce antD plugin and CSS style file in main.ts, use plugin in vue instance. Here we use the global reference method, of course, can also refer to the website for on-demand reference. (2 x.antdv.com/docs/vue/ge…

import { createApp } from 'vue'
import Antd from "ant-design-vue";
import App from './App.vue'
import router from './router/index'
import store from './store/index'
import "ant-design-vue/dist/antd.css";

createApp(App).use(router).use(store).use(Antd).mount('#app')
Copy the code

Using ant – design – vue

After the reference, we can use it in the component

<template>
  <a-button type="primary">button</a-button>
</template>
Copy the code

Install axios

Executing installation Commands

yarn add axios
Copy the code

Create a common request method

We put the utility class methods in the utils folder and create a file SRC /utils/request.ts

import axios from 'axios'

interface ApiConfig {
  body: object;
  data: object
}

async function request(url: string, options: ApiConfig) {
  // Create an axios instance
  const service = axios.create({
    baseURL: "".// api base_url
    timeout: 6000 // Request timeout
  });
  // Request interception
  service.interceptors.request.use(config= > {
    // You can set the request first-class information
    if (options && options.body) {
      config.data = options.body;
    }
    return config;
  });
  // Return interception
  service.interceptors.response.use(response= > {
    // You can format the returned data
    return response.data;
  });
  return service(url, options);
}
export default request;
Copy the code

Using the request method

<script>
import request from "@/utils/request.ts"

export default {
  mounted() {
    request('/api/getUser')
  }
}
</script>
Copy the code

Installing mock Tools

Mock data we use the MockJS plug-in, and the viet-plugin-mock plug-in needs to be installed in Vite.

Executing installation Commands

yarn add mockjs
yarn add vite-plugin-mock -D
Copy the code

Plugins are referenced in vite.config.ts

import { viteMockServe } from 'vite-plugin-mock'

export default defineConfig({
  plugins: [
    viteMockServe({ supportTs: true})],})Copy the code

Use the mock

Create the index.ts file in the SRC /mock file and add the following code sample

import { MockMethod } from 'vite-plugin-mock'
export default[{url: '/api/getList'.method: 'get'.response: () = > {
      return {
          code: 0.message: 'ok'.data: ['aa'.'bb'}}},]as MockMethod[]
Copy the code

This allows us to access mock data in the project using the request method, a public API request method created in the previous article.

import request from "@/utils/request.ts"

request('/api/getList').then(res= > {
  console.log(res);
})
Copy the code

The end of the

Well, here, a simple and practical Vite + VUe3 project is built, of course, front-end engineering is also essential code specification tools and unit testing tools, we can supplement according to need. Give it a try!