Vue3计算属性与监听属性和生命周期

文章目录

  • 一、计算属性与监视
    • 1、computed函数
    • 2、watch函数
    • 3、watchEffect函数
  • 二、生命周期
    • 1、与 2.x 版本生命周期相对应的组合式 API
    • 2、新增的钩子函数
    • 3、代码实例

一、计算属性与监视

1、computed函数

  • 与computed配置功能一致
  • 只有getter
  • 有getter和setter

2、watch函数

  • 与watch配置功能一致
  • 监视指定的一个或多个响应式数据, 一旦数据变化, 就自动执行监视回调
  • 默认初始时不执行回调, 但可以通过配置immediate为true, 来指定初始时立即执行第一次
  • 通过配置deep为true, 来指定深度监视

3、watchEffect函数

  • 不用直接指定要监视的数据, 回调函数中使用的哪些响应式数据就监视哪些响应式数据
  • 默认初始时就会执行第一次, 从而可以收集需要监视的数据
  • 监视数据发生变化时回调

二、生命周期

1、与 2.x 版本生命周期相对应的组合式 API

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

2、新增的钩子函数

组合式 API 还提供了以下调试钩子函数:

  • onRenderTracked
    • 注册一个调试钩子,当组件渲染过程中追踪到响应式依赖时调用。
    • 这个钩子仅在开发模式下可用,且在服务器端渲染期间不会被调用。
  • onRenderTriggered
    • 注册一个调试钩子,当响应式依赖的变更触发了组件渲染时调用。
    • 这个钩子仅在开发模式下可用,且在服务器端渲染期间不会被调用。

3、代码实例

<template>
<div class="about"><h2>msg: {{msg}}</h2><hr><button @click="update">更新</button>
</div>
</template><script lang="ts">
import {ref,onMounted,onUpdated,onUnmounted, onBeforeMount, onBeforeUpdate,onBeforeUnmount
} from "vue"export default {beforeCreate () {console.log('beforeCreate()')},created () {console.log('created')},beforeMount () {console.log('beforeMount')},mounted () {console.log('mounted')},beforeUpdate () {console.log('beforeUpdate')},updated () {console.log('updated')},beforeUnmount () {console.log('beforeUnmount')},unmounted () {console.log('unmounted')},setup() {const msg = ref('abc')const update = () => {msg.value += '--'}onBeforeMount(() => {console.log('--onBeforeMount')})onMounted(() => {console.log('--onMounted')})onBeforeUpdate(() => {console.log('--onBeforeUpdate')})onUpdated(() => {console.log('--onUpdated')})onBeforeUnmount(() => {console.log('--onBeforeUnmount')})onUnmounted(() => {console.log('--onUnmounted')})return {msg,update}}
}
</script>