Vue3的新特性( 二 )

    • 与 computed 配置功能一致
    • 只有 getter
    • 有 getter 和 setter
  • watch 函数
    • 与 watch 配置功能一致
    • 监视指定的一个或多个响应式数据 , 一旦数据变化,就自动执行监视回调
    • 默认初始时不执行回调,但可以通过配置 immediate 为 true,来指定初始时立即执行第一次
    • 通过配置 deep 为 true , 来指定深度监视
  • watchEffect 函数
    • 不用直接指定要监视的数据,回调函数中使用的哪些响应式数据就监视哪些响应式数据
    • 默认初始时就会执行第一次,从而可以收集需要监视的数据
    • 监视数据发生变化时回调
8) 生命周期与 2.x 版本生命周期相对应的组合式 API
  • beforeCreate -> 使用 setup()
  • created -> 使用 setup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeDestroy -> onBeforeUnmount
  • destroyed -> onUnmounted
  • errorCaptured -> onErrorCaptured
新增的钩子函数
【Vue3的新特性】组合式 API 还提供了以下调试钩子函数:
  • onRenderTracked
  • onRenderTriggered
09) 自定义 hook 函数
  • 使用 Vue3 的组合 API 封装的可复用的功能函数
  • 自定义 hook 的作用类似于 vue2 中的 mixin 技术
  • 自定义 Hook 的优势:很清楚复用功能代码的来源,更清楚易懂
  • 需求 1:收集用户鼠标点击的页面坐标
1 import { ref, onMounted, onUnmounted } from 'vue' 2 /* 3 收集用户鼠标点击的页面坐标 4 */ 5 export const useMousePosition=()=> { 6// 初始化坐标数据 7const x = ref(-1) 8const y = ref(-1) 910// 用于收集点击事件坐标的函数11const updatePosition = (e: MouseEvent) => {12x.value = https://www.huyubaike.com/biancheng/e.pageX13y.value = e.pageY14}1516// 挂载后绑定点击监听17onMounted(() => {18document.addEventListener('click', updatePosition)19})2021// 卸载前解绑点击监听22onUnmounted(() => {23document.removeEventListener('click', updatePosition)24})2526return { x, y }27 }2829 <template>30<div>31<h2>x: {{ x }}, y: {{ y }}</h2>32</div>33 </template>3435<script>36import { ref,setup } from 'vue'37 /* 在组件中引入并使用自定义hook38自定义hook的作用类似于vue2中的mixin技术39自定义Hook的优势:很清楚复用功能代码的来源, 更清楚易懂*/4041 import useMousePosition from './hooks/useMousePosition'4243 export default {44const { x, y } = useMousePosition()45return {46x,47y48}49 }50</script>

推荐阅读