今天给大家带来的的内容是compotion内的生命周期、计算属性、watch的使用
生命周期
vue3中生命周期在composition api中有一些小的改动
写法为
import { onMounted } from 'vue' setup () { console.log('内部的created') onMounted(() => { console.log('内部mounted') }) }
vue3中基本有大部分的周期,去掉了beforeCreate和created,不过我们可以在setup中直接写一些代码,这些代码相当于是created执行,我专门尝试了一下,composition api的周期和optionsAPI是不冲突的,会在options同周期之后执行
可以用下面代码进行测试
vue3对应vue2的周期为(compositionapi的周期都需要引入!!!):
- beforeCreate -> 使用setup()
- created -> 使用 setup()
- beforeMount -> onBeforeMount
- mounted -> onMounted
- beforeUpdate -> onBeforeUpdate
- updated -> onUpdated
- beforeDestroy -> onBeforeUnmount
- destroyed -> onUnmounted
- errorCaptured -> onErrorCaptured
- activated -> onActivated
- deactivated -> onDeactivated
好了,周期告一段落,基本常用的也就这几个,有以下几个周期发生变化:
1、beforeDestroy、destroyed 被替换为了onBeforeUnmount、onUnmounted
2、去掉了beforeCreate、created请直接使用setup
3、新增了onRenderTracked、onRenderTriggered(两个钩子都收到DebuggerEvent
类似于onTrack
和onTrigger
观察者的选项)
计算属性和watch
上完整代码:
import { reactive, watch, toRefs, computed,watchEffect } from 'vue' export default { setup () { const state = reactive({ count: 0, doubleCount: computed(() => { return state.count * 2 }), a: 1, watchCount: 0, watchCount1: 1 }) watchEffect(() => { console.log('watchEffect', state.count, state.a) }, { onTrack() { console.log('onTrack调用') // 当反应性属性或ref作为依赖项被跟踪时 }, onTrigger() { console.log('ontrigger调用') // 当观察程序回调由依赖项的变异触发时 } }) watch(() => { return [state.watchCount, state.watchCount1] }, (val, prev) => { console.log(val, prev) }) setTimeout(() => { state.watchCount++ }, 1000) const addRef = () => { state.count++ } return { // 将代理对象转换为纯对象。并对其每个key做包装,包装为ref ...toRefs(state), addRef, } } }
watch
API与2.x this.$watch
(以及相应的watch
选项)完全等效。watch
需要查看特定的数据源,并在单独的回调函数中应用副作用。默认情况下,它也是惰性的-即仅在监视的源已更改时才调用回调。
-
与相比
watchEffect
,watch
可以让我们: - 懒惰地执行副作用;
- 更具体地说明应触发观察程序重新运行的状态;
- 访问监视状态的先前值和当前值。
watchEffect是可以暂停的,可以将他赋值给一个变量,并且调用,如下:
const stop = watchEffect(() => { /* ... */ }) // later stop()
watchEffect 可以手动停止,而非一定要结束之后在停止