Build a VITE project

Vitejs. Cn/guide / # scaf…

The article is a little long, there is wrong place to write, please give directions to each big man, there is a problem to discuss and learn from each other

Create an empty template

/ / use the yarnYarn Create vite CD Enter project YARN// Install dependency packages
yarn run dev // Run the project
Copy the code

Create projects using templates

yarn create vite my-vue-app --template vue
Copy the code

The installation element – plus

/ / installation
yarn add element-plus 

/ / introduction
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

/ / register
const app = createApp(App)
app.use(ElementPlus)
Copy the code

The use of the setup

This thing was a little confusing at first

Setup can be used in two ways, one as a single-file component

<template>
    <p>{{msg}}<p>
</template>
<script setup>
	console.log('hello script setup')
	const msg = 'hello vue3';
</script>
Copy the code

Using object mode

Use object methods instead of using methods written on script tags

<script> export default {props: {title: String // accept parent component value}, setup(props, CTX)} </script>Copy the code

Use of components

You don’t need to use components, the filename is the component name, you don’t need the name attribute

<template>
    <child />
</template>

<script setup>
 import child from './child.vue'
</script>
Copy the code

Use keep-alive cache

vue3

Vue3.0 Component script-setup How to name components for keep-alive cache components

Website provides the include, exclude, Max parameter, website keep alive – document: v3.cn.vuejs.org/api/built-i…

Pay attention to

Include and exclude matches first check the name option of the component itself. If the name option is not available, match its locally registered name (the key value of the parent component’s components option). Anonymous components cannot be matched

The name is the name of the component, not the name specified in vue-router

<template>
    <div class="app-main">
        <router-view v-slot="{Component}">
            <keep-alive>
                <component :is="Component" />
            </keep-alive>
        </router-view>
    </div>
</template>


<script setup>
</script>
Copy the code

The KEEP-alive API has been cancelled

 <keep-alive>
   <router-view></router-view>
 </keep-alive>
Copy the code

Computed attribute computed

Get the returned value in the script tag, remember to use.value, to deconstruct is to get the value to deconstruct

import { computed } from 'vue'

const val = computed(() = > store.state.user.token)


// To get a specific value
const app = computed(() = > store.getters.app)
console.log(app.value, app.value.sidebar.opened)
Copy the code

The listener watch

import { reactive, watch } from 'vue'

const formData = reactive({
    userName: ' '.password: ' '
})
watch(formData, (newVal,oldVal) = > {
    console.log(newVal, newVal.password, oldVal, oldVal.password)
})
Copy the code

Reactive replaces the data function

The <script Setup > specification does not have the concept of a data function

import { reactive } from 'vue'

/ / use
const formData = reactive({
    userName: ' '.password: ' '
})
Copy the code

Ref base variable

The <script Setup > specification does not have the concept of a data function

import { ref } from 'vue'

/ / use
const user = ref('start')
Copy the code

Life hook function

Import hook function

Import the specified hook function with import {} from 'vue'Copy the code

Using hook functions

1 <script setup> import {onBeforeMount} from 'vue' onBeforeMount(() => {console.log(' call before instance mount: OnBeforeMount ')}) </script> // Usage 2 <script> export default {setup() {onMounted(() => {console.log('Component is mounted! ') }) } } </script>Copy the code

Vue3 hook function

Note: function changes

Moun is more visual than Destroy

BeforeDestroy replaced with onBeforeUnmount

Destroyed is replaced with onUnmounted

<template> <el-input v-model="inputVal"></el-input> </template> <script setup> import {ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onErrorCaptured, onActivated, onDeactivated, onRenderTracked, OnRenderTriggered} from 'vue' const inputVal = ref(") console.log('setup around beforeCreate and created life hook functions. No need to display definition ') onBeforeMount(() => {console.log(' Call before instance mount: onBeforeMount')}) onMounted(() => {console.log(' Call after instance mount: onBeforeMount: OnMounted ')}) onBeforeUpdate((val) => {console.log(' Call hook function before data update ', 'onBeforeUpdate',val)}) onUpdated(() => {console.log(' Call hook function after data update ', 'onUpdated')}) onBeforeUnmount(() => {console.log(' called before unmounting instance ', 'onBeforeUnmount')}) onUnmounted(() => {console.log(" Called before unmounting component instance ", OnErrorCaptured ((err) => {console.log(' Catching an error call from a descendant component ', 'onErrorCaptured')}) onRenderTracked(({key, Target, type}) => {console.log({key, target, type}) console.log(' trace virtual DOM rerendering calls ')}) target, type }) => { console.log({ key, target, Type}) console.log(' when the DOM is rerendered to triggerd.Similarly to renderTracked')}) onActivated(() => { Console. log(' keep-Alivie cache component activation is called, server rendering is not called ')}) onDeactivated(() => {console.log(' is called when keep-Alivie cache component is disabled, Server render does not call ')}) </script>Copy the code

DefineExpose exposes child component data

Expose the properties of the child component

child

<script setup> import {ref} from 'vue' const a = ref(' I am a subcomponent exporting value a') const b = ref(' I am a subcomponent exporting value b') defineExpose({a, b }) </script>Copy the code

Parent

You need to declare a ref property for the child component, then declare the variable in setup, and then read it in the hook function

<template> <p> parent </p> <defineExposeChild ref="childaa" /> </template> <script setup> import {ref, onMounted } from 'vue' import defineExposeChild from './defineExposeChild.vue' let childaa = ref(null); onMounted(() => { console.log(childaa.value.a) console.log(childaa.value.b) console.log(childaa.value.c); // return undefined}) </script>Copy the code

Reactive assigns a value to element

Because we can’t use this as we did with vue2, we can’t use const and let to direct the variables back to reactive. So: the method is simple, just modify the contents of the variable reference, as long as the object is not frozen

const roleInfo = reactive({data: { xxx: 'ooo' }})
/ / use the ref
const roleInfo = ref({xxx: 'ooo'})

// Update:
roleInfo.data = { xxx: 'aaa' }

/ / update:
roleInfo.value = { xxx: 'aaa' }
Copy the code

The practical application

<template> <el-table :data="departmentDataList.dataList" row-key="deptId" border> </el-table> </template> <script setup> Import {reactive} from 'vue' const departmentDataList = reactive({dataList: []})/tree/department list deptList ({}). Then (res = > {/ / el - table data change into interface returned data departmentDataList. The dataList = res. Data. The data}, Err => {console.log(' department tree ', err)}) </script>Copy the code

Discarded filters used recently

The official website has removed filters and replaced them with computed properties

New method: directly on the official website can be v3.vuejs.org/guide/migra…

<script>
// main.js
const app = createApp(App)

app.config.globalProperties.$filters = {
  currencyUSD(value) {
    return '$' + value
  }
}
</script>

<template>
  <h1>Bank Account Balance</h1>
  <p>{{ $filters.currencyUSD(accountBalance) }}</p>
</template>
Copy the code

Vue3 listens for route changes

Copy the code

The use of sass

yarn add sass sass-loader --dev
Copy the code

Element – plus mining pit

Slot-scope syntax deprecated

<el-table-column prop="deptName" label=" deptName" > <template #default="{row}"> {{row.deptName}} </template> </el-table-column>Copy the code

Vue3 mining pit

Parent and child components pass values

The parent component

Child component, no need to use components, filename is the component name

@setTitle is the emit event name defined by the child component to modify the parent component value

:title=”title” passes to the child component, which is the same as v2

<template> <child @settitle ="setTitleHe" :title="title" /> <el-alert title=" I am the parent component "type="success" /> <el-input V-model ="title" placeholder="Please input" /> <p> {{title}}</p> </template> <script setup> import {ref} from 'vue' import child from './child.vue' let title = ref('start1121') const setTitleHe = () => { console.log(val) title.value = val; } </script>Copy the code

Child components

defineEmits,defineProps is used without import

DefineProps accepts the parent component value. The arguments are objects. The key in the object is the accepted value and type

Passing a value to the parent component is a bit different: register the event name thrown: defineEmits([‘setTitle’]), and execute the event via the returned method: emits(‘setTitle’, ‘parent value changed ‘) // Pass the data to the parent component.

<template> <div @click="toEmits">Child Components</div> <p> {{title}}</p> </template> <script setup> // defineEmits,defineProps need not import, Const emits = defineEmits(['setTitle']) const {title} = defineProps({title: {type: String, defaule: 'defaule title' } }); Const toEmits = () => {emits('setTitle', 'modified parent ') // Pass data to parent} // Get data from parent console.log(title); // parent value </script>Copy the code

You can also register multiple events at defineEmits([‘setTitle’, ‘setContent’]) without having to compose them individually each time

const emits = defineEmits(['setTitle', 'setContent']) const toEmits = () => { emits('setTitle', Const setCon = () => {emits('setContent', 'parent content ') // Pass data to parent}Copy the code

bug

Before changing the value of the parent component through emits, you must register the name of the event thrown through defineEmits. Otherwise, warnings and errors must be changed through !!!!

Pay attention to

Be sure to register now and use it, don’t skip the steps of registration, I foolishly merged registration and use, mistake

Const emits = defineEmits(['setTitle', 'setContent']), const toEmits = () => {emits('setTitle', defineEmits(['setTitle', 'setContent']);Copy the code

defineEmits’ is not defined

.eslintrc.js

module.exports = {
  env: {
    'vue/setup-compiler-macros': true
  }
}
Copy the code

Element-plus is too large to pack

ome chunks are larger than 500 KiB after minification. Consider:

Good guy: just created a project, the introduction of a UI library, packaging more than 500KB, the project is big enough

To solve

Import element-Plus on demand

// Import components on demand
npm install -D unplugin-vue-components unplugin-auto-import

// Install viet-plugin-style-import component styles as needed
yarn add vite-plugin-style-import -D
Copy the code

vite.config.js

// Import modules in batches
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

import styleImport from 'vite-plugin-style-import';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    // Import components as needed
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
	
    // Import component styles as needed
    styleImport({
      libs: [{
        libraryName: 'element-plus'.esModule: true.resolveStyle: (name) = > {
          return `element-plus/theme-chalk/${name}.css`; },}]})],})Copy the code

The @scr directory was not recognized

Solution: vite. Config. Js

import path from "path";
export default defineConfig({
  resolve: {
    alias: {
       // Configure the SRC directory
      "@": path.resolve(__dirname, "src"),
       // Import another directory
      "components": path.resolve(__dirname, "src/components")}},plugins: [
    vue()
  ]
});
Copy the code

Or an array

import path from "path";
export default defineConfig({
  resolve: {
    alias: [{find: The '@'.replacement: path.resolve(__dirname, "src"),}, {find: 'components'.replacement: path.resolve(__dirname, 'src/components')}}],plugins: [
    vue()
  ]
});
Copy the code

The element-plus form cannot be entered

The name of the ruleForm attribute in the el-Form model conflicts with that of the ref attribute. If the ref attribute is called by another name, the model variable will remain unchanged, such as loginRefrule

<template> <div class="login"> <div class="container"> <el-form ref="ruleForm" :model="ruleForm" label-width="120px" Class ="demo-ruleForm"> <el-form-item label=" user name" prop="name"> <el-input V-model =" ruleform. name"></el-input> </el-form-item> <el-form-item label=" password" prop="password"> <el-input V-model =" ruleform. password"></el-input> </el-form-item> <el-form-item> <el-button type="primary">Create</el-button> <el-button >Reset</el-button> </el-form-item> </el-form> </div> </div> </template> <script setup> import {reactive } from "vue"; const ruleForm = reactive({ }) const getForm = () => { } </script>Copy the code

To solve

Only the value of the ref attribute differs from that of the model variable


<el-form ref="loginRefRule" :model="ruleForm">
</el-form>
Copy the code

The Vue3.0 child modifies the value passed by the parent

The parent component of a vue sub-component cannot be changed directly. You need to give the props value to the sub-component and then modify it.

Otherwise: Unexpected mutation of “props” prop.

Vue3 provides a solution: toRefs: v3.cn.vuejs.org/api/refs-ap…

ToRefs are useful so that the consumer component can deconstruct/expand the returned object without losing responsiveness

There is no need to use compute and watch to listen for changes

use

const { foo, bar } = reactive({
    foo: 1.bar: 2
})

Reactive does not respond to updates, and toRefs is required
const props = defineProps({
    drawerStatus: {
        type: Boolean}})const {drawerStatus} = toRefs(props)
Copy the code

Use toRefs for the solution

<template> <el-drawer V-model ="drawerStatus" title=" set department assistant ":before-close="handleClose"> <div class="drawer-footer"> <el-button> </el-button> <el-button type="primary" @click="onSubmit"> </el-button> </div> </el-drawer> </template> <script setup> import {reactive, toRefs} from 'vue' const props = defineProps({ drawerStatus: { type: Boolean } }) const emits = defineEmits(['upDrawerStatus']) const {drawerStatus} = toRefs(props) console.log(33333333, Reactive ({}) const onSubmit = () => {handleClose()} const handleClose = () => {console.log(' close drawer ') emits('upDrawerStatus', false)} </script>Copy the code

Modify the element-Plus component style

/deep/ does not work in vue

Solution: Replace depth selector with :: V-deep to take effect

:deep .login_tabs .el-tabs__nav{
    transform: translateX(37px) ! important;
}
Copy the code

Vite share configuration

Resolve. Alias Configures the alias of the system path

resolve: {
    alias: {
        "@": path.resolve(__dirname, "src"),
        "~": path.resolve(__dirname, "src/components")}}Copy the code

Resolve. extensions Specifies the extension that is ignored by the configuration

String array type: [‘ js’ and ‘ts’], and so on, combined with the vue suffix based on additional: [‘ MJS’, ‘js’ and’ ts’, ‘JSX’, ‘benchmark’, ‘json’, ‘vue’]

You are not advised to ignore the. Vue extension when importing vite, and the later version of VUE-CLI will not support ignoring the extension

Unsupported answers on Github github.com/vitejs/vite…

resolve: {
    extensions: {['.mjs'.'.js'.'.ts'.'.jsx'.'.tsx'.'.json'.'.vue']}}Copy the code

Vite configuration develops the service configuration

Vite. Config. Js: vitejs dev/config /

Server host IP address

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

// https://cn.vitejs.dev/config/#server-host
// Server. host set to 0.0.0.0 or true will listen on all addresses
export default defineConfig({
  plugins: [vue()],
  server: {
    host: true,}})Copy the code

Server. port Development port

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

// https://cn.vitejs.dev/config/#server-host
// Server. host set to 0.0.0.0 or true will listen on all addresses
export default defineConfig({
  plugins: [vue()],
  server: {
    host: true.port: 9527}})Copy the code

Server.proxy development port

import path from "path"

server: {
    proxy: { // Configure the proxy
      '/api': {
        target: 'http://47.106.135.141:8092'.// The destination address of the proxy to be used
        rewrite: path= > path.replace(/^\/api/.' '),
        changeOrigin: true,}}}Copy the code

Vite operation bug

Packing problem

What is packaged with vite is rendering chunks (30) and getting stuck

Github solution

Restore vite version to 2.5.10


eslint

The installation

// vsCode installs the ESLint extension

// Global installation
npm i -g eslint babel-eslint

// The project installs esLint dependencies
yarn add eslint babel-eslint eslint-plugin-vue -D

/ / install NPX
npm install -g npx

// Initialize the ESlint configuration with NPX in the project
npx eslint --init
Copy the code

ESLint vs Code configuration

Open plugins ===== and click extension Settings

Add the configuration

Every time you save it, you can handle code that doesn’t comply with the ESLint rules you configured in the.eslintrc.js file.

For example: configured to prohibit semicolons, code written semicolon, save when the semicolon will automatically kill.

code

Eslintrc provides corresponding rule configurations and explanations

. Eslintignore file

/node_modules/
/public/
.vscode
.idea
Copy the code

.eslintrc.js

module.exports = {
    "env": {
        "browser": true."es2021": true."node": true
    },
    "extends": [
        "eslint:recommended"."plugin:vue/essential"]."parserOptions": {
        "ecmaVersion": 13."sourceType": "module"
    },
    "plugins": [
        "vue"]./ * * * this option is to configure eslint validation rules, [enter the link just click on a configuration is that the path] * https://eslint.bootcss.com/docs/rules/ * /
    "rules": {
        "semi": [2.'never']."no-multiple-empty-lines": [
            "error", {
                "max": 2."maxEOF": 1}]."for-direction": "error"./**
         * eslint-plugin-vue 对vue的配置规则
         */
        // https://eslint.vuejs.org/rules/multi-word-component-names.html
        'vue/multi-word-component-names': [ 
            "error", {
                // Ignores component names. Set component names to allow, other non-hump names are incorrect
                ignores: [
                    'index'}],}}Copy the code

Process problems

module’ is not defined

"env": {
    "node": true // this configuration allows files to support module.exports, otherwise 'module' is not defined.
},
Copy the code

use

Where the configuration file uses extends”: “esLint :recommended to enable the recommended rule, and then the configuration item that is initialized is started

// "esLint :recommended" is started when initialized
module.exports = {
    "extends": [
        "eslint:recommended",]}Copy the code

For example, click for-direction

The syntax is written in the comments

"rules": {
    "for-direction": "error",
 }
Copy the code

BUG

Cannot find module ‘babel-eslint’ Cannot find module ‘babel-eslint’

Solution:

npm i -g eslint babel-eslint
Copy the code

vue-router4x

The use of the router

The installation

NPM info Vue-router versions View the vue-router version and download the latest version// Get the version number from this version information to install
npm install vue-router@4.03.
Copy the code

SCR directory

- src
  |- router
  |  |- index.js
  |- views
     |- Home.vue
     |- Contact.vue
Copy the code

index.js

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

// Enable history mode
// Vue2 uses mode: history
const routerHistory = createWebHistory();

const router = createRouter({
    history: routerHistory,
    routes: [{path: '/'.redirect: '/home'}]})export default router
Copy the code

Router hook function

Copy the code

The router configuration 404

Error: The jump to Vue-Router3X could not be matched with * : Catch all routes (“”) must now be defined using a param with a custom regexp.

CatchAll (.*) : /:catchAll(.*)

import {createRouter, createWebHashHistory} from 'vue-router'
const routes = [
  {
    path: "/".component: () = > import("@/layout/index.vue"),
    redirect: "/home".children: [{path: "/roleManage".name: "roleManage".icon: "".meta: {
          title: 'User Management'
        },
        component: () = > import(/* webpackChunkName: "roleManage" */"@/views/role-manage/index.vue"}]}, {path: '/error/404'.name: '404'.meta: {
      title: 'Page not found'
    },
    component: () = > import(/* webpackChunkName: "404" */ '.. /views/error/404.vue')},Path: '/:catchAll(.*)',
  {
    path: '/:catchAll(.*)'.ame: 'error404'.redirect: '/error/404'}]const router = createRouter({
  history: createWebHashHistory(),
  routes
})
export default router
Copy the code

vuex4x

Vuex installation is introduced

The installation

yarn add vuex@next --save 
Copy the code

Store directory in SCR directory

- store
  |- modules
  	|- user.js
  |- index.js
Copy the code

index.js

import { createStore } from 'vuex'

//import.meta. GlobEager imports all js files in modules
const files = import.meta.globEager('./modules/*.js')

const modules = {};
// Extract the js export from modules
for (const key in files) {
    if (Object.prototype.hasOwnProperty.call(files, key)) {
        modules[key.replace(/(\.\/|\.js)/g.' ').replace('modules/'.' ')] = files[key].default
    }
}
/ / create a store
const store = createStore({
    modules
})

export default store;
Copy the code

User.js, this is not that different from v2

Const state = {token: 'I am token', name: '' } const mutations = { } const actions = { } const getters = { } export default { namespace: true, state, mutations, actions, getters }Copy the code

Main.js is no different from v2

import store from './store'

const app = createApp(App);
app.use(store)
Copy the code

Login. vue, using store

First export useStore from vuex, then use the value returned by the useStore function

<template> <div class="content"> {{val}}</p> </div> </template> <script setup> import { computed } from 'vue' import { useStore } from 'vuex' const store  = useStore() const val = computed(() => store.state.user.token) </script>Copy the code

Vue3 Pin Scan code login latest solution

Mainly use method and step pit bar, pit step quite big, vue3 step pit together can discuss with each other ha

Pay attention to the comments, a lot of attention in the comments and summary

Add import to index.html

<script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js"></script>
Copy the code

Other code

/ / API. Export function scanCode (params) {return request({url: '/auth', method: 'get', params})}Copy the code

The login. Vue code

Consider an example: the core implementation code

// Add a div with the id login_container <div style="" class="qrCode" id="login_container"> </div> <script setup> import to the login page {reactive, ref, onMounted, watch } from "vue" import {useRouter, useRoute} from "vue-router" import {useStore} from 'vuex' import { scanCode } from '@/api/login' let goto = encodeURIComponent('https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=appid&response_type=code&scope=snsapi_l Ogin&state =STATE&redirect_uri= your project vue project address or the address of the page you sent to remember the same url in the pin callback otherwise you can't log in ') let tmpAuthCode = window.location.search.split("&")[0].split("=")[1] onMounted(() => { DDLogin({ id: "Login_container ", // you need to define an HTML tag on your page and set the ID, For example, <div id="login_container"></div> or <span id="login_container"></span> goto: goto, // please refer to the way in the comment style: "border:none; background-color:#FFFFFF;" , width: "270", height: "370" }) let handleMessage = function (event) { let origin = event.origin console.log("origin", Event. Origin) if (origin = = "https://login.dingtalk.com") {/ / determine whether from ddLogin scan code. Let loginTmpCode = event.data // Get the loginTmpCode to create a jump link for the jump. Href = decodeURIComponent(goto + "&logIntmpCode =" + loginTmpCode)}} if (Typeof) window.addEventListener ! = 'undefined') {if (tmpAuthCode){// Store. Dispatch ('scanCodeLogin', {code: TmpAuthCode, state: 'auth'}). Then (res = > {the console. The log (' success 'res) window. The location. The href =' http://192.168.0.235:2021/ '; Redirect_uri = redirect_uri = redirect_uri = redirect_uri = redirect_uri The address of redirect_URI should be the address of your project, }, err => {console.log(' failed ', err)})} window.addEventListener('message', handleMessage, false) } else if (typeof window.attachEvent ! = 'undefined') { window.attachEvent('onmessage', handleMessage) } }) </script>Copy the code

Nail end configuration

Redirect_uri specifies the address at which the front-end VUE starts, as shown in red

The problem summary

Redirect_uri address must be started with a vue of consistent, that is to say must be localhost + port: http://localhost:2021/, your local IP + port: http://192.168.1.215:2021/;

Redirect_uri addresses must be handled through encodeURIComponent

1, tread the backend to use penetration problem, there is a problem there will be a 302 redirect problem [is jump redirect_uri after login, and then get the backend interface is not reality, because the redirect can’t jump is the backend address front-end control] pass;

2, after the front end uses the nail penetration, put the penetration address to the back end of the nail callback URL, so it is really a scan code login can open the vUE project, but!! There is a very, very serious problem when you put vue’s traversal address in the pin callback URL: Vite will not match the domain name used by vue when the domain name is opened: Reload () triggers window.location.reload().

2 solution is: localhost + port: http://localhost:2021/, your local IP + port: http://192.168.1.215:2021/; Localhost is unnecessary. Configure the IP

This situation takes up the problem, yesterday was good today can not penetrate the problem: the solution is [actually already do not need to penetrate, in the nail developer platform configuration callback redirect_URI address is the front-end VUE project qidong address can, and then the front-end will not need to penetrate]

// This port is the port after the vUE project is started. ding -config=ding.cfg -subdomain=start 9527 cd windows_64 ding -config=ding.cfg -subdomain=abcde 8080Copy the code

Question effect:

**** Error Version 1.7/1.7 Forwarding 127.0.0.1:4044 Forwarding 127.0.0.1:4044 Web Interface 127.0.0.1:4040 # Conn 0 Avg Conn Time 0.00 msCopy the code

There is also the back-end interface:

Zhangsan.vaiwan.com This interface address is the back end of the peanut shell through, do not use IP

service.interceptors.request.use((config) = > {
    if (store.getters.token){
        config.headers['Authentication'] = getCookie('token')}else {
        console.log(config)
        if (config.url.includes('/auth')){
            config.baseURL = 'http://zhangsan.vaiwan.com'}}console.log("Intercept", config)
    return config
}, (error) = > {
    return Promise.reject(error)
})
Copy the code

Summary of troubleshooting steps

First, through packaging, determine whether the development environment has a problem or whether the page reloads are only periodic when the project is running. [Fixed] It will not refresh after locating to package

This issue touches on: Vite and updated source code: Vite principle: HMR and Live Reload

More vite hot update principle, webSocket to connect, overloading mainly in handleHMRUpdate responsible for the code update logic, when the detection file can not hot update, can only be loaded, that is, the refresh, but this defect vite does not do the cutoff mechanism and error reporting.