5 minutes to build vite + vue3 project, simple and practical!

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 hurry up and try it!

Create vite project

Execute the create command

Execute the vite project creation command, and select vue+ts mode during navigation creation.

yarn create vite
yarn
yarn dev
 Copy code

Modify vite profile

When vite is run from the command line, vite will automatically resolve the project root directory named vite config. JS file. Here, let's simply set the proxy settings that must be made for @ pointing to src and joint debugging with the backend during development. For other configuration parameters, please refer to the official website. (cn.vitejs.dev/config/)[1]

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path' // The editor prompts that the path module cannot be found. You can yarn add @types/node --dev

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

Installing Vue router

Execute installation command

yarn add vue-router@4
 Copy code

Create router file

Create Src / router / index TS file. When creating a route, it is recommended to use route lazy loading to optimize access performance.

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

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: () => import('@/views/Home.vue') // It is recommended to load routes lazily to optimize access performance
  },
  {
    path: '/demo',
    name: 'demo',
    component: () => import('@/views/Demo.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router
 Copy code

Introducing router

In main use router in vue example in TS file

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

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

Using the router view component

On app The route view component is used in the Vue file, and the route matching component will be rendered through the route view component.

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

Installing vuex

Execute installation command

yarn add vuex@next
 Copy code

Create store file

Create 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 code

Introducing vuex

In main The vue example in the TS file uses store, 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 code

Install UI library Ant Design Vue

Execute installation command

yarn add ant-design-vue@next
 Copy code

Reference Ant Design Vue

In main The ant D plug-in and css style file are introduced into ts, and the use plug-in is used in Vue instance. Here we use the global reference method. Of course, you can also refer to the official website for on-demand reference. (2x.antd v.com/docs/vue/ge…[2]

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 code

Using Ant Design Vue

After reference, we can use it in the component

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

Installing axios

Execute installation command

yarn add axios
 Copy code

Create public request method

We put the tool class methods in the utils folder and create the 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 => {
    // Request header information can be set here
    if (options && options.body) {
      config.data = options.body;
    }
    return config;
  });
  // Return intercept
  service.interceptors.response.use(response => {
    // Here, you can format the returned data
    return response.data;
  });
  return service(url, options);
}
export default request;
Copy code

Use request method

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

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

Install the mock tool

For mock simulation data, we select the mockjs plug-in, and the vite plugin mock plug-in needs to be installed in vite.

Execute installation command

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

vite. config. Reference plug-ins in TS

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

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

Using mock

Create index. In the src/mock file TS file, add the following code example code

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 code

In this way, we can access mock data in the project. Here, we use the public api request method request created in the previous article.

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

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

end

Well, here, a simple and practical vite + vue3 project is completed. Of course, code specification tools and unit testing tools are also essential in the front-end project. You can supplement them as needed. Try it!

From: fleshy siege lion

https://juejin.cn/post/7009145360694116382

Added by kigroy on Thu, 23 Dec 2021 14:07:59 +0200