Vue3.0 —— 生命周期函数与setup
1,Vue3.0 生命周期函数变更 Vue2.x beforeCreate created
beforeMount(挂载前) mounted(挂载后)
beforeUpdate(数据更新前)
updated(数据更新后)
beforeDestroy(销毁前)
destroyed(销毁后)
Vue3.0
setup
onMounted(挂载后)
onBeforeUpdate(数据更新前)
onUpdated(数据更新后)
onBeforeUnmount(销毁前)
onUnmounted(销毁后)
2、setup
在Vue2.x中,我们实现一个功能,需要在data中新增数据,在methods/computed/watch中新增业务逻辑,数据和业务逻辑是分离的,不利于管理,为了解决这个弊端,Vue3.0推出了Composition API(组合API),也叫做注入API,实际上setup中定义的数据和业务逻辑,会注入到data和methods中
setup()是组合API的入口函数,可以直接在里面定义变量和方法(数据和业务逻辑),通过对象的形式返回暴露出去
执行时机
setup执行顺序是在beforeCreate之前的,网上很多说是在beforeCreate和create之间,其实是错误的
setup中使用生命周期函数
从vue中引入生命周期函数后,在setup入口函数中使用
import { onMounted } from 'vue';
export default {
setup() {
// 2、 setup入口函数中使用
onMounted(() => {
console.log(11)
})
},
// !! 也可以结合vue2.x的写法
beforeMount() {
console.log(22);
}
}
</script>