vue3.0新特性初体验(二)上

简介: vue3.0新特性初体验(二)上


watchEffect

接受一个函数,当依赖改变时,重新调用该函数。

const count = ref(0)
watchEffect(() => console.log(count.value))
setTimeout(() => {
  count.value++
}, 100)

watchEffect()在setup()或生命周期钩子中被调用时,监听就始终存在该组件的生命周期中,直到组件unmount.

另一种卸载监听的情况是,watchEffect()返回一个stop handler,调用该handler即可停止监听。

const stop = watchEffect(() => {
  /* ... */
})
// later
stop()

当向后台获取数据时,watchEffect()接受async回调函数。

const data = ref(null)
watchEffect(async () => {
  data.value = await fetchData(props.id)
})

组件的update函数也有watch effect。用户定义的watchEffect会在组件update之后再去调用。

<template>
  <div>{{ count }}</div>
</template>
<script>
  export default {
    setup() {
      const count = ref(0)
      watchEffect(() => {
        console.log(count.value)
      })
      return {
        count
      }
    }
  }
</script>

上述代码,第一轮会同步打印count.value(在onmount生命周期前); 当count发生改变时,先执行组件更新,然后再去log.

如果想将watchEffect中的回调函数第一次执行,放在onmount后,

onMounted(() => {
  watchEffect(() => {
    // access the DOM or template refs
  })
})

如果想让watchEffect()调用发生在组件update前,或re-run同步,需要传递一个带有flush属性(默认值为post)的option对象。

watchEffect(()=> {
//...
}, {
 flush: 'sync'  // 在更新前触发 flush: "pre"
})

此外,option对象还有ontrack和ontrigger两个函数属性,用于调试watcher的行为。

  • onTrack will be called when a reactive property or ref is tracked as a dependency
  • onTrigger will be called when the watcher callback is triggered by the mutation of a dependency
watchEffect(
  () => {
    /* side effect */
  },
  {
    onTrigger(e) {
      debugger   // 进行交互式调试
    }
  }
)


watch

等价于vue 2.x中的this.$watch.

相比于watchEffect(), watch()可帮我们实现:

  • Perform the side effect lazily;
  • Be more specific about what state should trigger the watcher to re-run;
  • Access both the previous and current value of the watched state.

watch()的数据源可以是一个返回值的getter函数,或者是一个ref对象。

// watching a getter
const state = reactive({ count: 0 })
watch(
  () => state.count,
  (count, prevCount) => {
    /* ... */
  }
)
// directly watching a ref
const count = ref(0)
watch(count, (count, prevCount) => {
  /* ... */
})

对于多数据源的监听,可借助数组。

watch([fooRef, barRef], ([foo, bar], [prevFoo, prevBar]) => {
  /* ... */
})

生命周期钩子

可以使用直接导入的onXXX功能注册生命周期钩子:

import { onMounted, onUpdated, onUnmounted } from 'vue'
const MyComponent = {
  setup() {
    onMounted(() => {
      console.log('mounted!')
    })
    onUpdated(() => {
      console.log('updated!')
    })
    onUnmounted(() => {
      console.log('unmounted!')
    })
  }
}

这些生命周期钩子注册功能只能在期间同步使用setup()(只能在setup()中调用),因为它们依赖于内部全局状态来定位当前活动实例(当前setup()正在被调用的组件实例)。在没有当前活动实例的情况下调用它们将导致错误。

2.x生命周期选项和3.0Composition API之间的映射

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

新钩子

除了2.x生命周期等效项之外,3.0Composition API还提供了以下调试挂钩:

  • onRenderTracked
  • onRenderTriggered

两个钩子都收到DebuggerEvent类似于onTrackonTrigger观察者的选项:

export default {
  onRenderTriggered(e) {
    debugger
    // inspect which dependency is causing the component to re-render
  }
}


相关文章
|
1月前
|
JavaScript 前端开发 开发者
Vue第1天:特性概览
Vue第1天:特性概览
21 1
|
5月前
|
JavaScript 算法 编译器
Vue3的新特性
Vue3的新特性
|
5月前
|
缓存 JavaScript
Vue3 的模板语法:指令、插值语法和其他相关特性
Vue3 的模板语法:指令、插值语法和其他相关特性
107 4
Vue3 的模板语法:指令、插值语法和其他相关特性
|
9天前
|
开发框架 JavaScript 算法
了解vue3的基本特性和底层原理
Vue3的底层原理涵盖了响应式系统的Proxy-based实现、组件的模板编译与渲染更新机制、组合式API带来的逻辑组织变革,以及其他关键特性的具体实现。这些原理共同构成了Vue3强大、高效、灵活的现代前端开发框架基础。
21 2
|
16天前
|
JavaScript 前端开发 编译器
Vue 3:新特性与改进技术详解
【4月更文挑战第25天】Vue 3 提升了编译和运行时性能,引入了Composition API实现灵活代码复用,新增Teleport用于任意位置渲染,支持Fragment多根节点及Suspense处理异步组件。同时,TypeScript支持增强,自定义指令和全局API也得到优化。Vue 3的新特性旨在提供更高效、灵活的开发体验,持续引领前端技术发展。
|
23天前
|
JavaScript 前端开发 API
Vue3有哪些新特性
【4月更文挑战第15天】 Vue3带来了显著性能提升和开发体验优化:更快的渲染速度、更小的捆绑体积、改进的内存管理、增强的TypeScript支持、引入Composition API提升代码复用性,以及使用Proxy改进响应式数据处理。这些特性使Vue3成为更高效、灵活和可靠的框架,为开发者创造高性能应用提供了强大工具。
11 0
|
1月前
|
JavaScript 前端开发
Vue 中setup的特性
Vue 中setup的特性
|
1月前
|
JavaScript 前端开发 编译器
vue3带来的新特性/亮点
vue3带来的新特性/亮点
14 0
|
6月前
|
JavaScript 前端开发 编译器
你知道Vue 3.0中Treeshaking特性吗?
你知道Vue 3.0中Treeshaking特性吗?
106 0
|
4月前
|
JavaScript 前端开发 API
Vue.js 3.0新特性解读:开启前端开发新纪元
Vue.js作为前端开发中备受欢迎的框架,近期推出了全新的3.0版本,本文将对Vue.js 3.0的新特性进行深入解读,带领读者探索前端开发的新纪元。