Vue 3.x基础


Vue 3.x基础

模版






setup API

变量(响应式)

// 基本数据类型
let refValue = ref(1)
console.log(refValue.value) // 1

// 复杂数据类型
let reactiveValue = reactive({ a: 1, b: 2 })
console.log(reactiveValue) // { a: 1, b: 2 }

// 解构toRefs,一般用于reacative创建的变量
const { a, b } = toRefs(reactiveValue)
console.log(a, b) // 1, 2

函数

// 创建
const changeValue = (v) => {
    refValue.value = v
    console.log(v) // 1
}
// 调用
changeValue(1)

生命周期

选项式 API Setup API 调用时机
beforeCreate Not needed* #
created Not needed* #
beforeMount onBeforeMount(常用) 在挂载开始之前被调用:相关的 render 函数首次被调用。
mounted onMounte(常用) 组件挂载时调用
beforeUpdate onBeforeUpdate 数据更新之前调用,此时DOM还未更新
updated onUpdated DOM 重新渲染和打补丁,此时DOM已更新,不要在该钩子函数里更新数据。
beforeUnmount onBeforeUnmount 在卸载组件实例之前调用。此时Vue实例仍是正常的。
unmounted onUnmounted 卸载组件实例后调用,组件实例的所有指令、事件侦听器都被移、子组件实例都会被卸载。
activated onActivated 被 keep-alive 缓存的组件激活时调用。
deactivated onDeactivated 被 keep-alive 缓存的组件停用时调用。
errorCaptured onErrorCaptured 当捕获一个来自子孙组件的错误时被调用,此钩子可以返回 false 以阻止该错误继续向上传播。
renderTracked onRenderTracked #
renderTriggered onRenderTriggered #

注意:因为 setup 是++围绕 beforeCreate 和 created++ 生命周期钩子运行的,所以不需要显式地定义它们。换句话说,在这些钩子中编写的任何代码都应该直接在 setup 函数中编写。


计算属性、侦听器


路由



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

const routes = [
  {
    path: '/',
    redirect: '/home'
    // component: () => import('../pages/home.vue') // 组件懒加载
  }
  ...
]

// 创建路由实例
const router = createRouter({
  history: createWebHashHistory(), // 使用 hash 模式
  routes, // `routes: routes` 的缩写
})

export default router


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

const app = createApp(App)
app.use(router) // 挂载路由到Vue



pinia

Vuex替代品,全局数据管理器



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

// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
export const usePiniaStore = defineStore('user', () => {
  // vue3 setup编程模式,让结构更加扁平化
  const _this = window.$this

  // state
  const userId = ref('111122')
  const userData = ref(null)

  // action
  const getUser = async () => {
    const res = await _this.$api.getId()
    userData.value = res.data
  }
  
  // getter
  const userName = computed(() => userData.value.id + ' ---- ')

  // 导出
  return { userData, userName, getUser, userId }
})



vue