Vue3 has been around for a while now, so today I’m going to try it out by starting with a build project
Make sure you have Node.js installed successfully on your computer. To use the Vite build tool, node.js version >= 12.0.0 is required
View the Node.js version
node -v
Copy the code
Use Vite to quickly initialize the project prototype
Use NPM:
npm init @vitejs/app
Copy the code
Using Yarn:
yarn create @vitejs/app
Copy the code
Then complete the following operations as prompted:
- Enter the project name
The name of this project is the default viet-project
- Select a template
This project requires Vue3, so we choose VUE and Vue3 will be installed automatically. Choose JavaScript
- The creation is complete if the following appears
Then follow the steps
CD vite-project // Go to the file directory NPM install // Install depends on NPM run dev // to start the projectCopy the code
Modify the Vite configuration file
The Vite configuration file vite.config.ts is located in the root directory and is automatically read when the project is started.
This project first do some simple configuration, such as: set @ to SRC directory, service start port, packaging path, proxy, etc.
For more configuration items and usage of Vite, visit the official website vitejs.dev/config/
Import {defineConfig} from 'vite' import vue from '@vitejs/plugin-vue' // If the editor says path module cannot be found, You can install it @ types/node - > NPM I @ types/node - D import {resolve} from export 'path' / / https://vitejs.dev/config/ default DefineConfig ({plugins: [vue()], resolve: {alias: {'@': resolve(__dirname, 'SRC ') // set '@' to' SRC '}}, base: './', // Set the package path server: {port: 4000, // Set the service startup port number open: true, // Set whether to automatically open the browser cORS when the service starts: True / / allow cross-domain/agent/set, according to the actual circumstance of our project configuration / / proxy: {/ / '/ API: {/ / target:' http://xxx.xxx.xxx.xxx:8000 ', / / changeOrigin: true, // secure: false, // rewrite: (path) => path.replace('/api/', '/') // } // } } })Copy the code
Integrated routing tool Vue Router
-
Install Vue3 supported routing tool vue-router@4
npm i vue-router@4 Copy the code
-
Create the SRC /router/index.ts file
Create router directory SRC and create index.ts file in router directory:
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router' import Home from '@/views/home.vue' const routes: Array<RouteRecordRaw> = [ { path: '/', name: 'Home', component: Home }, { path: '/vuex', name: 'Vuex', component: import('@/views/vuex.vue') } ] const router = createRouter({ history: createWebHashHistory(), routes }) export default router Copy the code
Depending on the routing configuration of this project, you will need to create a view directory under SRC to store page components.
We create home.vue and vuex.vue in the views directory.
-
Mount the routing configuration in the 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
Vuex integrated status management tool
-
Install Vue3 supported status management tool vuex@next
npm i vuex@next Copy the code
-
Create the SRC /store/index.ts file
import { createStore } from 'vuex' const defaultState = { count: 0 } // Create a new store instance. export default createStore({ state() { return defaultState }, mutations: { increment(state: typeof defaultState) { state.count++ } }, actions: { increment(context) { context.commit('increment') } }, getters: { double(state: typeof defaultState) { return 2 * state.count } } }) Copy the code
-
Mount the Vuex configuration in main.ts
import { createApp } from 'vue' import App from './App.vue' import store from './store/index' createApp(App).use(store).mount('#app') Copy the code
Integrated UI framework Element Plus
-
Install Element Plus, a UI framework that supports Vue3
npm i element-plus Copy the code
-
Mount Element Plus in main.ts
import { createApp } from 'vue' import App from './App.vue' import ElementPlus from 'element-plus' import 'element-plus/lib/theme-chalk/index.css' createApp(App).use(ElementPlus).mount('#app') Copy the code
Integrate the HTTP tool Axios
-
Install Axios (Axios is not directly related to Vue version, just install the latest version)
npm i axios Copy the code
-
Configuration Axios
To keep the project directory structured and formal, we created the utils directory under SRC to store our common utility functions.
Axios as an HTTP tool, we create axios.ts as an Axios configuration file in the utils directory:
import Axios from 'axios' import { ElMessage } from 'element-plus' const baseURL = 'https://api.github.com' const axios = Axios.create({ baseURL, timeout: 20000 / / request timeout 20 s}) / / front interceptor (before a request to intercept) axios. Interceptors. Request. Use ((response) = > {/ * * * according to the actual circumstance of your project to do processing * config Nothing is done to config here, Return */ return response}, (error) = > {return Promise. Reject (error)}) / / rear interceptor (access to the response when the intercept) axios. Interceptors. Response. Use ((response) = > {/ * * * Do response and error based on what your project is doing * I'm not doing anything with response and error, Return */ return response}, (error) => { if (error.response && error.response.data) { const code = error.response.status const msg = error.response.data.message ElMessage.error(`Code: ${code}, Message: ${msg}`) console.error(`[Axios Error]`, error.response) } else { ElMessage.error(`${error}`) } return Promise.reject(error) } ) export default axiosCopy the code
-
Using Axios
In the need to use Axios file, import the Axios configuration file as follows:
<template></template> <script lang="ts"> import { defineComponent } from 'vue' import axios from '.. /utils/axios' export default defineComponent({ setup() { axios .get('/users/XPoet') .then((res) => { console.log('res: ', res) }) .catch((err) => { console.log('err: ', err) }) } }) </script>Copy the code
This completes the construction of the project. Vue-router is configured, AXIos Vuex is configured, and third-party UI component libraries can be configured according to your needs