preface

Start the 2021 learning journey, mainly introduces the actual process of learning VitE2 and VUE3. Vite2 + Vue3+Element-Plus + VUE-Router4 + Vuex + Eslint

Introduce vite

Vite (French for "fast", pronounced /vit/) is a new front-end build tool. It consists of an out-of-the-box development server plus a set of build instructions. Vite leverages the browser's native ES module support and esBuild-based dependency prepackaging to significantly improve the front-end development experience. Copy the codeCopy the code

Initialize the project

# NPM 6. X NPM init @vitejs/app my-vue-app --template vue # NPM 7+ NPM init @vitejs/app my-vue-app -- --template vue # yarn yarn create @vitejs/app my-vue-app --template vue copy codeCopy the code

The alias set

Modify the vite. Config. Js

import path from 'path' export default defineConfig({ ... , resolve: { alias: { '@': path.resolve(__dirname, 'src'), components: path.resolve(__dirname, 'src/components'), assets: path.resolve(__dirname, 'src/assets'), views: path.resolve(__dirname, 'src/views'), utils: path.resolve(__dirname, 'src/utils'), apis: Path.resolve (__dirname, 'SRC /apis'),},}}) copies the codeCopy the code

SCSS pretreatment

SCSS is a CSS preprocessing language and an upgraded version of SASS. SCSS is a new syntax introduced by SASS 3. Its syntax is fully compatible with CSS3 and inherits the powerful functions of SASS.

Install the sass

NPM I -d sass node-sass sass-loader Copies the codeCopy the code

Introduce SASS global variables/styles

# vite.config.js export default defineConfig({ ... , css: { preprocessorOptions: { scss: {/ / @ / SRC/alias / / so it is assumed that you have a ` SRC/assets/SCSS/variables. The SCSS ` additionalData this file: `@import "@/assets/scss/variables.scss"; '},},}}) copies the codeCopy the code

ElementUI

Start introducing the UI framework, using Element to fit the VUe3 version of Element-Plus

The installation element

NPM i-s element-plus copy codeCopy the code

Load components as needed

Use viet-plugin-style-import to load components on demand to reduce project size

Install \ textrm \ color {red} {vite – plugin – style – import} vite – plugin – style – import

NPM install vite-plugin-style-import -d Copy the codeCopy the code

Modify \ textrm \ color {red} {vite. Config. Js} vite. Config. Js

import styleImport from 'vite-plugin-style-import' plugins: [ vue(), styleImport({ libs: [ { libraryName: 'element-plus', esModule: true, ensureStyleFile: true, resolveStyle: (name) => { name = name.slice(3); return `element-plus/packages/theme-chalk/src/${name}.scss`; }, resolveComponent: (name) = > {return ` element - plus/lib / ${name} `;},},], copying code})]Copy the code

Create a new element.js file

// If you want to use.scss style files, SCSS file // import 'element-plus/packages/theme-chalk/ SRC /base. SCSS 'import 'element-plus/packages/theme-chalk/src/base.scss' import { ElAlert, ElAside, ElAutocomplete, ElAvatar, ElBacktop, ElBadge, ElBreadcrumb, ElBreadcrumbItem, ElButton, ElButtonGroup, ElCalendar, ElCard, ElCarousel, ElCarouselItem, ElCascader, ElCascaderPanel, ElCheckbox, ElCheckboxButton, ElCheckboxGroup, ElCol, ElCollapse, ElCollapseItem, ElCollapseTransition, ElColorPicker, ElContainer, ElDatePicker, ElDialog, ElDivider, ElDrawer, ElDropdown, ElDropdownItem, ElDropdownMenu, ElFooter, ElForm, ElFormItem, ElHeader, ElIcon, ElImage, ElInput, ElInputNumber, ElLink, ElMain, ElMenu, ElMenuItem, ElMenuItemGroup, ElOption, ElOptionGroup, ElPageHeader, ElPagination, ElPopconfirm, ElPopover, ElPopper, ElProgress, ElRadio, ElRadioButton, ElRadioGroup, ElRate, ElRow, ElScrollbar, ElSelect, ElSlider, ElStep, ElSteps, ElSubmenu, ElSwitch, ElTabPane, ElTable, ElTableColumn, ElTabs, ElTag, ElTimePicker, ElTimeSelect, ElTimeline, ElTimelineItem, ElTooltip, ElTransfer, ElTree, ElUpload, ElInfiniteScroll, ElLoading, ElMessage, ElMessageBox, ElNotification, } from 'element-plus'; const components = [ ElAlert, ElAside, ElAutocomplete, ElAvatar, ElBacktop, ElBadge, ElBreadcrumb, ElBreadcrumbItem, ElButton, ElButtonGroup, ElCalendar, ElCard, ElCarousel, ElCarouselItem, ElCascader, ElCascaderPanel, ElCheckbox, ElCheckboxButton, ElCheckboxGroup, ElCol, ElCollapse, ElCollapseItem, ElCollapseTransition, ElColorPicker, ElContainer, ElDatePicker, ElDialog, ElDivider, ElDrawer, ElDropdown, ElDropdownItem, ElDropdownMenu, ElFooter, ElForm, ElFormItem, ElHeader, ElIcon, ElImage, ElInput, ElInputNumber, ElLink, ElMain, ElMenu, ElMenuItem, ElMenuItemGroup, ElOption, ElOptionGroup, ElPageHeader, ElPagination, ElPopconfirm, ElPopover, ElPopper, ElProgress, ElRadio, ElRadioButton, ElRadioGroup, ElRate, ElRow, ElScrollbar, ElSelect, ElSlider, ElStep, ElSteps, ElSubmenu, ElSwitch, ElTabPane, ElTable, ElTableColumn, ElTabs, ElTag, ElTimePicker, ElTimeSelect, ElTimeline, ElTimelineItem, ElTooltip, ElTransfer, ElTree, ElUpload, ]; const plugins = [ ElInfiniteScroll, ElLoading, ElMessage, ElMessageBox, ElNotification, ]; const option = { size: 'small', zIndex: = > {3000} export default (app)/element/global configuration app. Config. GlobalProperties. $element = option components.forEach((component) => { app.component(component.name, component); }); plugins.forEach((plugin) => { app.use(plugin); }); }; Copy the codeCopy the code

Modify the main js

import useElement from '@/utils/element.js'; Const app = createApp(app) useElement(app) app.mount('#app'Copy the code

Matters needing attention

Error: @use rules must be written before any other rules. # modify viet.config.js - additionalData: `@import "assets/scss/variables.scss"; ` + additionalData: `@use "assets/scss/variables.scss" as *; 'Copy codeCopy the code

vue-router

Vue Router is a routing manager of Vue. It is deeply integrated with the core of Vue. Js and is one of the core plug-ins of Vue.

Install the vue – the router

NPM i-S [email protected] Copy the codeCopy the code

Create a router directory and file

Creating a Router Directory

Create a router directory folder in the SRC directory

A new index. Js

Create index.js in the router directory

Import {createRouter, createWebHistory} from "vue-router"; Import Layout from '@/ Layout '/** * Define route array */ const routes = [{// 404 Route name: '404', path: '404', Component: () = > import (' / @ / views/error / 404. Vue ')}, {/ / 401 routing name: '401', path: '401', component: () => import('@/views/error/401.vue'), hidden: true }, { name: 'home', path: "home", component: () => import("/@/views/home/home.vue"), } ]; /** * createRouter */ const router = createRouter({hash mode: createWebHashHistory, // history mode: createWebHistory: createWebHistory("/"), // history:createWebHashHistory(), routes, }); /** * Router. BeforeEach ((guard) => {beforeEach. CheckAuth (guard, router); }); /** * Router.onError ((handler) => {console.log("error:", handler); }); /** * export default router Copy codeCopy the code

Modify the main js

import { createApp } from 'vue' import App from './App.vue' import useElement from '@/utils/element.js'; Import router from '@/router/index.js' const app = createApp(app) useElement(app) app.use(router) app.mount('#app'Copy the code

vuex

Install vuex

NPM I vuex@4 -s copy the codeCopy the code

Create a Store directory and file

Creating a Store directory

Create a store directory under the SRC directory

Create a new index.js file

Create an index.js file in the store directory

import { createStore, Store } from 'vuex'; import user from './modules/user'; import getters from './getters' const store = createStore({ modules: { user }, getters }); Export Default Store copies the codeCopy the code

Create the modules directory and module file

// src/store/modules/user.js const state = { name: 'hello vue3', age: 18 } const mutations = { SET_NAME: (state, name) => { state.name = name }, SET_AGE: (state, age) => { state.age = age } } const actions = { setName({ commit }, name) { commit('SET_NAME', name) }, SetAge ({commit}, age) {commit('SET_AGE', age)}} export default {namespaced: true, state, mutations, actions} copy the codeCopy the code

Modify the main js

import { createApp } from 'vue' import App from './App.vue' import useElement from '@/utils/element.js'; import router from '@/router/index.js' import i18n from '@/i18n/index.js' import store from '@/store/index.js' //++++ Use (router) app.use(store) //++++ app.use(i18n) useElement(app) app.mount('#app') Copy codeCopy the code

internationalization

Internationalization through VUE-I18N

Install the vue – i18n

NPM I vue-i18n@next -s copy the codeCopy the code

Example Add the i18N configuration file

Create the i18n directory in the SRC directory and create the cn.js and en.js multi-language configuration files

// SRC /i18n/cn.js export default {message: {hello: 'hello, welcome to use Vue3'}}; // src/i18n/en.js export default { message: { hello: 'Hello Vue3' } }; Copy the codeCopy the code

Add i18N entry file

Create index.js in the i18n directory

// src/i18n/index.js import { createI18n } from 'vue-i18n'; import cn from './cn.js'; import en from './en.js'; const messages = { en: { ... en }, 'zh-cn': { ... cn } } const i18n = createI18n({ locale: localStorage.getItem('lang') || 'zh-cn', messages }); export default i18n; Copy the codeCopy the code

Modify the main js

import { createApp } from 'vue' import App from './App.vue' import useElement from '@/utils/element.js'; import router from '@/router/index.js' import i18n from '@/i18n/index.js' const app = createApp(App) app.use(router) App.use (i18n) useElement(app) app.mount('#app'Copy the code

ESLint

In the process of coding, code specification is very important, using ESLint can avoid many coding errors, improve the code readability, here uses Airbnb JavaScript code specification.

Install eslint

NPM I -d eslint eslint-config-airbnb-base eslint-plugin-import eslint-plugin-vue copies the codeCopy the code

Add the.eslintrc.js configuration file

Module. Exports = {extends: module. Exports = {extends: module. ['plugin:vue/vue3-essential', 'airbnb-base'], parserOptions: { sourceType: 'module', ecmaVersion: 2020, }, plugins: ['vue'], rules: { ... }}; Copy the codeCopy the code

Configure the. Eslintignore file

# configure ESLint to ignore files and create.eslintignore files in the root directory, where you can add configurations as required, such as /node_modules /dist copy codeCopy the code

conclusion

After one or two days, we basically operated according to the official website guide and completed the construction step by step.

Portal to the future

Architecture design based on Vue

Nodejs version management

Vscode development tool optimization