个人web开发经验

JavaScript · Vue 框架代码片段

把常用的 Vue 写法收进一个页面

个人在 web 开发中积累的一些经验,主要内容为 JavaScript 语言的 Vue 框架的代码片段。按主题整理,方便查阅、复制和回顾。

Vue 3Composition API<script setup>Vue RouterPinia性能优化

快速开始

创建项目

npm create vite@latest my-app -- --template vue
cd my-app
npm install
npm run dev

入口文件

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

createApp(App).mount('#app')

响应式基础

ref 与 reactive

import { ref, reactive, toRef } from 'vue'

const count = ref(0)
count.value++

const form = reactive({ name: '', age: 18 })
form.name = 'Vue'

// reactive 直接解构会丢失响应性
const { name } = form            // 不推荐
const nameRef = toRef(form, 'name') // 推荐

解构整个对象

import { reactive, toRefs } from 'vue'

const state = reactive({ loading: false, list: [] })
const { loading, list } = toRefs(state)

loading.value = true
list.value.push({ id: 1 })

计算属性与侦听

computed

import { ref, computed } from 'vue'

const price = ref(100)
const count = ref(2)

const total = computed(() => price.value * count.value)

// 可写计算属性
const fullName = computed({
  get: () => `${firstName.value} ${lastName.value}`,
  set: (val) => {
    const [first, last] = val.split(' ')
    firstName.value = first
    lastName.value = last
  },
})

watch 与 watchEffect

import { watch, watchEffect } from 'vue'

watch(count, (val, old) => {
  console.log(`count: ${old} -> ${val}`)
})

watch(
  () => state.user,
  (user) => console.log('user 变化', user),
  { deep: true }
)

watchEffect(() => {
  console.log('依赖自动收集:', count.value)
})

生命周期

组合式 API 中的生命周期

import { onMounted, onBeforeUnmount, onUnmounted } from 'vue'

onMounted(() => {
  console.log('组件已挂载')
})

onBeforeUnmount(() => {
  console.log('销毁前,适合清理副作用')
})

onUnmounted(() => {
  console.log('组件已卸载')
})

组件通信

props 与 emit

<script setup>
const props = defineProps({
  title: { type: String, required: true },
  count: { type: Number, default: 0 },
})

const emit = defineEmits(['update', 'close'])
emit('update', props.count + 1)
</script>

v-model 组件

<!-- 子组件 -->
<script setup>
const model = defineModel()
</script>

<template>
  <input v-model="model" />
</template>

<!-- 父组件 -->
<MyInput v-model="keyword" />

provide / inject

// 祖先组件
provide('theme', ref('dark'))

// 后代组件
const theme = inject('theme', ref('light'))

插槽

默认、具名与作用域插槽

<!-- 子组件 -->
<slot />
<slot name="header" :user="user" />

<!-- 父组件 -->
<Card>
  <template #header="{ user }">
    <strong>{{ user.name }}</strong>
  </template>

  <p>默认插槽内容</p>
</Card>

组合式函数

useFetch

import { ref, onMounted } from 'vue'

export function useFetch(url) {
  const data = ref(null)
  const error = ref(null)
  const loading = ref(false)

  async function load() {
    loading.value = true
    error.value = null
    try {
      const res = await fetch(url)
      if (!res.ok) throw new Error(`HTTP ${res.status}`)
      data.value = await res.json()
    } catch (e) {
      error.value = e
    } finally {
      loading.value = false
    }
  }

  onMounted(load)
  return { data, error, loading, reload: load }
}

useLocalStorage

import { ref, watch } from 'vue'

export function useLocalStorage(key, initial) {
  const saved = localStorage.getItem(key)
  const value = ref(saved ? JSON.parse(saved) : initial)

  watch(value, (v) => localStorage.setItem(key, JSON.stringify(v)), { deep: true })
  return value
}

Vue Router

路由与守卫

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

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', component: () => import('./views/Home.vue') },
    { path: '/about', component: () => import('./views/About.vue'), meta: { auth: true } },
  ],
})

router.beforeEach((to) => {
  if (to.meta.auth && !isLogin()) return '/login'
})

取参数与跳转

import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

console.log(route.params.id, route.query.tab)
router.push({ name: 'detail', params: { id: 1 } })

Pinia 状态管理

Option Store

import { defineStore } from 'pinia'

export const useCounter = defineStore('counter', {
  state: () => ({ n: 0 }),
  getters: {
    double: (state) => state.n * 2,
  },
  actions: {
    inc() {
      this.n++
    },
  },
})

Setup Store

import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useUser = defineStore('user', () => {
  const name = ref('')
  const upper = computed(() => name.value.toUpperCase())

  function setName(v) {
    name.value = v
  }

  return { name, upper, setName }
})

模板技巧

v-for 与条件渲染

<li v-for="item in list" :key="item.id">{{ item.name }}</li>

<div v-if="loading">加载中…</div>
<div v-show="visible">频繁切换用 v-show</div>

动态组件与 Teleport

<component :is="currentView" />

<Teleport to="body">
  <Modal v-if="open" />
</Teleport>

性能优化

减少不必要的响应式开销

import { shallowRef, markRaw } from 'vue'

// 大对象只关心整体替换
const bigData = shallowRef(hugeObject)
bigData.value = await fetchBigData()

// 明确不需要响应式的第三方实例
const chart = markRaw(echarts.init(el))

v-memo 缓存子树

<div v-for="item in list" :key="item.id" v-memo="[item.selected]">
  {{ item.name }}
</div>

常见坑

DOM 更新后取尺寸

import { nextTick } from 'vue'

visible.value = true
await nextTick()
console.log(el.value.offsetHeight)

两个高频问题

// 1. reactive 解构后不是响应式
const { count } = reactive({ count: 0 })   // 错
const count = toRef(state, 'count')        // 对

// 2. 侦听对象内部变化需要 deep
watch(state, handler, { deep: true })
粤ICP备2020089753号-1