Vue.js

Notes taken while reviewing the Vue ecosystem, covering Vue2, ElementUI, Vuex, Vue3, Pinia, Vite, and ElementPlus. I lost part of the file halfway through and hastily filled in a few gaps (about how to develop the good habit of saving your work frequently).

Contents

Vue2

This document only records key points. For systematic study, please refer to the official documentation.

Two features of the Vue framework:

Data-driven views, bidirectional data binding

MVVM

MVVM is the core principle behind Vue’s implementation of data-driven views and bidirectional data binding.

MVVM: model view viewmodel

<img src="/api/file/694b7938355d4084897239c0502b673e.png" alt="image-20240612151423706" style="zoom: 50%;" />

viemodel is the core of MVVM. It binds the view and model together, enabling bidirectional data binding.

Event

To access the native DOM event object in Vue’s @click, do the following:

<button  @click='fun(1,$event)'>...</button>

$event is a built-in Vue variable whose value is the native DOM event object.

If a function has no parameter list, a variable is provided by default as the first argument to store the DOM event object.

Event modifiers

Example: prevent the default event

<button @click.prevent='fun(1,$event)'>...</button>

Modifiers:

Modifier Event
prevent Prevents the default behavior
stop Stops propagation
capture Triggers the current event handler in capture mode
once Triggers only once
self Prevents the event from propagating; only triggers its own event

Filter

Filters are defined under the filters node and can only be used in interpolation syntax and v-bind.

Define a filter:

filters:{
    testFilter(text){
        log(text)
        return 'test'
    }
}

Usage

{{message | testFilter}}
v-bind:id="message | testFilter"

The result will be the filter’s return value.

Global filters:

To share a filter between multiple components, create a global filter using Vue.filter(filter name, filter function).

example:

<template>
  <div>
    <h1>{{ msg | testFilter}}</h1>
    <h1>{{ msg | test}}</h1>
  </div>
</template>

<script>
import Vue from 'vue';
export default {
  props: {
    msg: String
  },
  filters:{
    testFilter(msg){
      return msg.toUpperCase()
    }
  }
}
Vue.filter('test',()=>{
  return 'test'
})
</script>

Chained filters (filter chain):

{message | filterA | filterB | filterC}

Watch

A watch listener can listen for data changes and perform corresponding actions.

Definition

  • Method-style listener
    • Cannot be triggered automatically after the page has finished loading
    • Cannot observe an object's properties
  • Object-style listener
    • Can be triggered automatically after the page has finished loading by configuring the immediate parameter
    • Configure deep to watch deeply

Example:

<template>
  <div class="hello">
    <div class="container">
      <input type="text" v-model="username">
      <div class="tip" v-show="check"> 数据不合法</div>
      <input type="password" v-model="password">
      <input type="submit" value="Login ">
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      check: false,
      username: 'example',
      password: '',
    }
  },
  watch: {
    username(newValue, oldValue) {
      if (newValue.length < 6)
        this.username = oldValue
    }
  }
}
</script>
 watch: {
    // 对象写法
    password:{
      handler(newValue, oldValue){
        console.log(newValue,oldValue);
      },
      immediate:true //自动触发 
    }
}

Axios

A library focused on network requests

Use async/await and destructuring assignment to simplify data retrieval.

<template>
  <div class="hello">
    <button @click="getData"> get data </button>
    <br>
    {{ page }}
    {{ total }}
    <br>
   <img class="avatar" v-for="item,index in data" :key="index" :src="item.avatar"/>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      page: 0,
      total: 0,
      data: [],
    }
  },
  methods:{
    async getData(){
      let { data:{page, total,data} } = await axios.get('https://reqres.in/api/users?page=2')
      // 重命名 data 到 res防止混乱
      // let { data:res } = ...
      this.data = data
      this.page = page
      this.total = total
    }
  },
}

</script>

<style scoped>
.hello {
  padding: 10px;
  height: 100%;
}
.avatar{
  height: 60px;
  width: 60px;
  object-fit: cover;
  margin-left: 10px;
  border-radius: 30px;
}
</style>

SPA

SPA stands for Single Page Application (Sinple Page Application).

It refers to a website that has only one unique HTML page.

Vue-cli

vue-cli is the standard development tool for Vue.js. It simplifies the process of using webpack to create a production-ready Vue project.

scoped

When modifying child component styles with scoped, use /deep/ to make the styles apply to child components as well.

/deep/ .el-button{
    ...
}

LifeCycle

  • Creation phase
    • before create
    • created
    • beforeMount
    • mounted
  • Running phase
    • beforeUpdate
    • updated
  • Destruction phase
    • beforeDestroy
    • destroyed

Props

Custom properties for passing data from parent to child

Props make it easy to pass data from a parent component to a child component, but the values passed are read-only. Changes made by the child component are not passed back to the parent.

When passing an object, you can still modify its properties in the parent component. This is not recommended and violates design principles.

$emit

Custom events can be used to pass data from child to parent.

#在子组件中调用$emit('事件名',参数)
#在父组件中通过 v-on:事件名 @事件名 ="接收数据的函数"来接收数据完成对应的操作

example

#子组件
...
  this.$emit('sendMsg',this.tempMsg)
...
#父组件

 <chat-send-component class="input" @sendMsg="sendMsg"></chat-send-component>
...
 methods:{
    sendMsg(msg){
        this.records.push(msg)
     }
}

EventBus

Create a separate Vue instance, then use $emit and $on to send and receive data, enabling data transfer between sibling components.

This approach is called EventBus.

Array

  • forEach((item, index) => {})
    • The forEach method iterates over each element in an array and executes the provided callback function. It does not return a value.
  • some((item) => { return boolean })
    • The some method checks whether at least one element in an array satisfies the provided test function. If an element satisfies the condition, it returns true; otherwise, it returns false.
  • every((item) => { return boolean })
    • The every method checks whether all elements in an array satisfy the provided test function. If all elements satisfy the condition, it returns true; otherwise, it returns false.
  • reduce((accumulator, currentValue) => { return newValue }, initialValue)
    • The reduce method applies a reduction function you provide to each element in an array (from left to right), combining the results into a single return value. It takes two arguments: the reduction function and the initial value.
  • filter((item) => { return boolean })
    • The filter method creates a new array containing all elements that pass the provided test function.
  • map((item) => { return newValue })
    • Creates a new array in which each element is the return value of calling the provided callback function.

Vue Router

redirect: redirect (configured in the route rules)

{
    path:"/",redirect:"/home"
}

How to Configure Nested Routes

{
    path:"/",component:HomePage,
    children:[
        ...子级路由规则
    ]
}

Default Child Route

If the path of a route rule in a child route is an empty string, that route rule is triggered when the parent route is accessed.

This kind of rule is called a default child route.

Append-Mode Navigation

<router-link :to="{path:'child1',append:true}">inner chat</router-link>

Path parameters

在path中使用英文冒号定义动态参数
# 1
{
    path: '/movie/:id',
    component: MoviePage
}
# 2
{
    path: '/movie/:id',
    component: MoviePage
    props: true
}

Accept Path Parameters

# 1
{{ $route.params.id }}
# 2
props:['id']

Query Parameters

Pass them using ?key:value

Receive them using $route.query.key

$route also provides fullPath (including query parameters) and path (excluding them)

Programmatic Navigation

$router.push() 跳转到指定的地址,并增加一条历史记录
$router.replace()  跳转到指定的地址,并替换掉当前的地址(不可以back退回)
$router.go(Number) 前进或者后退指定数量的地址
$router.back()/forward() 后退或者前进一次

Global Before Guard

router.beforeEach((to, from, next)=>{
    // to 是将要访问的路由的信息对象
    // from 是将要离开的路由的信息对象
    // next 是一个函数,调用 next() 表示放行,允许这次路由导航
    // next('/login') 改变目标地址并放行
    // next(false) 拒绝本次跳转
})

ElementUI

Installation

pnpm i 'element-ui'

Automatic Introduction

### 安装如下依赖,必须限定版本
pnpm i [email protected]
pnpm i [email protected]

Configure the CLI

const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const {ElementPlusResolver} = require('unplugin-vue-components/resolvers')
module.exports = defineConfig({
    transpileDependencies: true, configureWebpack: {
        plugins: [AutoImport({
            resolvers: [ElementPlusResolver()],
        }), Components({
            resolvers: [ElementPlusResolver()],
        }),],
    }
})

At this point, automatic configuration is complete, but some components, such as icons, may still need to be imported manually.

VueX

Concepts

Vuex is a state management tool built for Vue.

Concepts:

  • state, the data source that drives the application;
  • view, declaratively maps state to the view;
  • actions, respond to state changes caused by user input on the view.
npm install vuex 

The core of every Vuex application is the store. A “store” is essentially a container that holds most of the state in your application. Vuex differs from a plain global object in two ways:

  1. Vuex state storage is reactive. When a Vue component reads state from the store, if the state in the store changes, the corresponding component is efficiently updated as well.
  2. You cannot directly change the state in the store. The only way to change it is to explicitly commit a mutation. This makes it easy to track every state change, allowing us to build tools that help us better understand our application.

Basic Usage

  1. Install
npm i vuex@^3  #限定安装版本为3,供vue2使用,否则将安装最新版
  1. Configuration

Create a store folder in the root directory to manage state, then import it globally in main.js.

import Vue from 'vue'
import Vuex from 'vuex'
import { getItem, setItem } from '@/utils/storage-util'

Vue.use(Vuex)

// actions 用于响应组件中的动作
const actions = {
  login (context, user) {
    context.commit('setLoginUser', user)
  },
  logout (context) {
    context.commit('setLoginUser', '')
  }
}
// mutations 用于操作state
const mutations = {
  setLoginUser (state, user) {
    state.loginUser = user
    setItem('loginUser', user)
  }
}
// state 用于存储数据
const state = {
  loginUser: getItem('loginUser')
}
// getter 用于获取数据
const getters = {
  getLoginUser (state) {
    return state.loginUser
  },
  isLogin (state) {
    return !!state.loginUser
  }
}
export default new Vuex.Store({
  actions: actions,
  mutations: mutations,
  state: state,
  getters: getters
})
  1. Introduction
import store from '@/store'

new Vue({
  store,
  render: (h) => h(App)
}).$mount('#app')

How to Read Global State

// 1
computed: {
    user () {
        return this.$store.state.loginUser
    }
}
// 2
computed: {
    ...mapState(['loginUser'])
},
// 3
computed: {
    ...mapState({
      user: 'loginUser'
    })
},

Modify Global State

  1. Components call actions through dispatch.

  2. Actions call mutations.

  3. Mutations ultimately operate on state (mutations do not support asynchronous operations).

Modules

In the basic usage pattern, all components in a project share and maintain a single object. This is clearly not very elegant. Vuex provides the modules property, which lets you split the object into modules according to certain rules, making the structure clearer!

Usage (based on the original approach)

Split out the original state, mutations, actions, and getters, and organize them by module.

Name the modules and place them in modules to complete the module split.

For mutations and getters within a module, the first argument they receive is the module's local state object.

For actions within a module, the local state is exposed through context.state, while the root state is context.rootState:

const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

Namespaces Dynamic Module Registration Module Reuse

I don’t think I’ll need this; I’ll learn it later after I pass.

Best Practices for Large Projects:

├── index.html
├── main.js
├── api
│   └── ... # 抽取出API请求
├── components
│   ├── App.vue
│   └── ...
└── store
    ├── index.js          # 我们组装模块并导出 store 的地方
    ├── actions.js        # 根级别的 action
    ├── mutations.js      # 根级别的 mutation
    └── modules
        ├── cart.js       # 购物车模块
        └── products.js   # 产品模块

Strict Mode

In strict mode, an error will be thrown whenever a state change occurs that was not caused by a mutation function. This ensures that all state changes can be tracked by debugging tools.

const store = new Vuex.Store({
  // ...
  strict: true
})

Vue3

Lifecycle

Vue 3 introduced the Composition API, which changed the lifecycle hooks.

  vue2          vue3
beforeCreate  -> 使用 setup()
created 	  -> 使用 setup()
beforeMount   -> onBeforeMount
mounted 	  -> onMounted
beforeUpdate  -> onBeforeUpdate
updated 	  -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed 	  -> onUnmounted
errorCaptured -> onErrorCaptured

image-20240723091044570

The execution times of each lifecycle, as shown above

template

Vue 3 supports components with multiple root elements

Unlike Vue 2, which allows only one root element

<script setup>

Manually exposing a large number of states and methods in the setup() function is tedious. Fortunately, we can avoid this by using Single-File Components (SFCs). We can use <script setup> to greatly simplify the code.

Communication Between Components

  • props 父=>子 pass immutable data
  • Custom events 子=>父
  • Global event bus 任意组件 implemented with mitt
  • v-model 父<=>子 is written on the component tag to implement props and custom events
  • ref 子=>父: child components need to expose mutable data
    $parent 父=>子: parent components need to expose mutable data
  • provide & inject 父=>子=>孙
  • pinia 任意组件: an official Vue 3 solution for communication between arbitrary components, with Composition and Options API styles
  • Slots 父<=>子: use different slot types as needed

Vite

A next-generation build tool, known for its speed

Optimizes chunk files

Usage

npm create vite@latest
yarn create vite
# 按照提示信息创建即可

Environment Variables and Modes

Vite exposes environment variables on a special import.meta.env object, and these variables are statically replaced at build time.

.env Files

Vite uses dotenv to load additional environment variables from the following files in your envDir:

.env                # 所有情况下都会加载
.env.local          # 所有情况下都会加载,但会被 git 忽略
.env.[mode]         # 只在指定模式下加载
.env.[mode].local   # 只在指定模式下加载,但会被 git 忽略

Please note that if you want to use the $ symbol in an environment variable, you must escape it using \.

KEY=123
NEW_KEY1=test$foo   # test
NEW_KEY2=test\$foo  # test$foo
NEW_KEY3=test$KEY   # test123

To use them in your project, only variables prefixed with VITE_ will be exposed to code processed by Vite.

VITE_SOME_KEY=123

Configure Automatic Browser Opening

"scripts": {
    "dev": "vite --open",
    "build": "vue-tsc -b && vite build",
    "preview": "vite preview"
},

Configure src Path Aliases

Note: Vue: Cannot find module node:path or its corresponding type declarations

Please update WebStorm to version 24 (so many pitfalls)

  1. Configure vite.config.ts
import { resolve } from 'node:path'
export default defineConfig({
  resolve: {
    alias: {
      // @ 替代为 src
      '@': resolve(__dirname, 'src'),
      // @component 替代为 src/component
      '@components': resolve(__dirname, 'src/components'),
    },
  },
})
  1. Configure tsconfig.app.json
{
  "compilerOptions": {
    /* path */
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"],
      "@components": ["src/components/*"],
    }
  }
}

If you still get errors after completing the configuration, try restarting the WebStorm language service, or simply restart WebStorm.

SVG Plugin

  • Install

    pnpm i -D vite-plugin-svg-icons
    
  • Configure vite

      plugins: [
        createSvgIconsPlugin({
          // 指定需要缓存的图标文件夹
          iconDirs: [resolve(__dirname, 'src/assets/icons')],
          // 指定symbolId格式
          symbolId: 'icon-[dir]-[name]',
        }),
      ],
    
  • Configure main.ts

    import 'virtual:svg-icons-register'
    
  • Save the SVG file in the /src/assets/icons folder

  • Use it in the component

    <svg style="width: 20px; height: 20px;">
        <use xlink:href="#icon-tool" />
    </svg>
    

Eslint

Configure the Eslint tool for the project

"lint": "eslint .",
"lint:fix": "eslint . --fix"

Then simply answer the corresponding questions.

A note about an issue I encountered while installing ESLint dependencies:

 ERR_PNPM_EPERM  EPERM: operation not permitted...

Solution: Close VS Code or WebStorm to release the file lock, then run the command again.

ESLint Best Practices

pnpm dlx @antfu/eslint-config@latest

Configure WebStorm for Automatic Fixes

Enable automatic ESLint monitoring in Settings, then enable lint on save for a seamless development experience.

Husky

The configuration above helps us maintain code quality during development. However, if we overlook something, we may still commit code that doesn't meet the standards to the remote repository, and other team members may also commit code that doesn't meet the standards.

To solve this problem, we can use Husky to extend Git operations with hooks. Using the appropriate hook lets us format or fix the project's ESLint issues before committing code.

  1. Install Husky

    npx husky init
    
  2. After execution is complete, modify /.husky/pre-commit

    pnpm run lint:fix
    
  3. Commit code to Git and automatically fix existing issues

commit lint

Checks whether commit messages comply with the standards

Type Description
build Release version
chore Change the build process, or add dependencies, tools, etc.
ci Continuous integration changes
docs Documentation changes
feat New features
fix Fix issues
perf Performance-related optimizations, such as improving speed or user experience
refactor Code refactoring
revert Revert to the previous version
style Code formatting changes
test Test case changes

Pnpm

A fast, disk-space-efficient package manager

Compared with npm and Yarn, it has significant advantages in handling dependencies and installation speed

  • Installation
npm i -g pnpm
  • Set the dependency storage location
pnpm config set store-dir D:\\tool\\.pnpm-store
  • Create a project
pnpm create vite
  • Restrict the project’s package manager
    • Configure a script to check whether the package manager is pnpm; if not, exit
    • Configure the script to run before install (preinstall)

Mock

Fake data by intercepting axios requests.

  • Installation

    pnpm i -D [email protected] mockjs
    
  • Configure Vite

    viteMockServe({
        localEnabled: command === 'serve',
    }),
    
  • Create a mock folder and create index.ts.

    import type { MockMethod } from 'vite-plugin-mock'
    
    const arr: any = []
    for (let index = 0; index < 20; index++) {
      arr.push({
        customer_name: 'wade',
        status_text: '登录成功',
        os: 'Windows 10',
        browser: 'Chrome(99.0.4844.51)',
        ip: '192.168.9.110',
        created: '2021-12-14 10:41:02',
        location: '局域网 局域网',
      })
    }
    
    const logList = {
      total: 31,
      page: 1,
      page_size: 20,
      list: arr,
    }
    
    const statusList = {
      data: [
        { label: '全部', value: 0 },
        { label: '待审核', value: 1 },
      ],
    }
    
    export default [
      {
        url: '/mock/api/getList',
        method: 'post',
        response: () => {
          return logList
        },
      },
      {
        url: '/mock/api/getStatusList',
        method: 'get',
        response: () => {
          return statusList
        },
      },
    ] as MockMethod[]
    
  • Test axios

    pnpm i axios
    
  • Writing request

    axios.get('/mock/api/getStatusList').then((res) => {
      console.log(res)
    })
    
  • Check the console

    {"data":[{"label":"全部","value":0},{"label":"待审核","value":1}]}
    

Axios

axios: Front-end network request tool

Basic Usage

  1. Install

    pnpm i axios
    
  2. Encapsulation

    // 一般放在src的util目录下的request文件夹中
    import axios from 'axios'
    
    const request = axios.create({
      // 通过环境变量读取api配置
      baseURL: import.meta.env.VITE_BASE_URL, 
      timeout: 5000,
    })
    
    export default request
    
  3. Create an API

    import request from '@/util/request'
    
    export function login(username: string, password: string) {
      // console.log(username, password)
      return request.post('/login', { username, password })
    }
    

Interceptors

Used to perform common operations before and after requests.

// 在请求前,执行的操作 通常用于放置token
request.interceptors.request.use((config) => {
  config.headers.token = '####test'
  return config
})

request.interceptors.response.use((response) => {
  // 成功回调
  return response
}, (error) => {
  // 失败回调
  const status = error.response.status
  let message = ''
  switch (status) {
    case 401:
      message = '登录过期,请重新登录。'
      break
    case 403:
      message = '权限不足,无法访问。'
      break
    case 500:
      message = '服务器内部错误'
      break
    default:
      message = '网络异常'
  }
  ElMessage({
    type: error,
    message,
  })
  return Promise.reject(error)
})

Pinia

Installation

pnpm i pinia

Introduction

app.use(createPinia())

Create Store Option

import {defineStore} from "pinia";

interface counterStore {
    count: number
}

export const useCounterStore = defineStore('counter', {
    state: (): counterStore => ({
        count: 0
    }),
    getters: {
        double: (state) => 2 * state.count
    },
    actions: {
        increment() {
            this.count++
        },
    },
})

Usage

<template>
  <div class="container">
    <div class="count">
      count: {{counterStore.count}}
    </div>
    <el-button size="default" type="primary" @click="counterStore.increment()">Increment</el-button>
  </div>

</template>

<script setup lang="ts">
import {useCounterStore} from "../../store";

const counterStore = useCounterStore()
</script>

Create store setup

export const useCounterStore = defineStore('counter', () => {
  // state
  const count = ref(0)
  // getters
  const doubleCount = computed(() => count.value * 2)
  // actions
  function increment() {
    count.value++
  }

  return { count, doubleCount, increment }
})

Element Plus

Installation

 pnpm install element-plus

Automatic Import

npm install -D unplugin-vue-components unplugin-auto-import

Vite Configuration

// webpack.config.js
const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const { ElementPlusResolver } = require('unplugin-vue-components/resolvers')

module.exports = {
  // ...
  plugins: [
    AutoImport({
      resolvers: [ElementPlusResolver()],
    }),
    Components({
      resolvers: [ElementPlusResolver()],
    }),
  ],
}

Configuring automatic imports can reduce the bundle size and eliminate unused code.

Problem

Elmessage styles are not automatically imported, so they cannot be displayed correctly.

Solution: Import them in app.vue.

import 'element-plus/lib/components/message/style/css'