vue3 的setup和生命周期

许多文章认为setup执行时间在beforeCreate 和created 之间,但是通过实际测试发现setup调用在beforecreate之前。

export default {beforeCreate() {console.log('beforeCreate running....');},created() {console.log("created running");},mounted() {console.log("mounted running");},setup() {let info = ref(0);const ins = getCurrentInstance();console.log('setup running....');return{}}}

执行结果:

setup确确实实是最先执行了。
在vue3中setup代替了beforeCreate和created,函数里面无法使用data和methods方法中的数据。setup是集成性api,setup中定义的变量和方法,如在template模板中使用,变量需要使用ref或者reactive关键字定义,并且将使用到的方法和变量return出去,不然页面没有效果还报错的。

  • ref 用于定义基本数据加粗样式类型,比如string、number、boolean等。ref的本质其实还是reactive,当我们给ref函数传递一个值之后,ref函数会自动的转化成{value: xx},只是中间自动帮我们套了一层value。const name = ref(1) => name: {value: 1}
  • reactive用于定义复杂数据类型,比如数组、对象等。

在setup 中,有9个旧的生命周期钩子可以访问:

beforeCreate -> use setup()
created -> use setup()
其中setup函数是整合 created跟 beforeCreat
beforeMount ->onBeforeMount (挂载前)
mounted -> onMounted (挂载后)
beforeUpdate -> onBeforeUpdate**(更新前)**
updated -> onUpdated (更新后)
beforeDestroy -> onBeforeUnmount ( 销毁前)
destroyed ->onUnmounted ( 销毁后)

通过解构赋值的方式即可引入:

import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onActivated, onDeactivated, onErrorCaptured } from 'vue'export default {setup() {onBeforeMount(() => {// ... })onMounted(() => {// ... })onBeforeUpdate(() => {// ... })onUpdated(() => {// ... })onBeforeUnmount(() => {// ... })onUnmounted(() => {// ... })onActivated(() => {// ... })onDeactivated(() => {// ... })onErrorCaptured(() => {// ... })}}

setup 函数将接收两个参数,props&context

注意:setup函数里面是没有this对象的,使用它的话会报 undefined。

  • setup 函数将接收两个参数,props&context
    第一个参数props,主要是用来获取属性传值,在使用之前必须现在Vue的props属性中先声明,才能在setup函数的第一个参数中获取到。
<template><ButtonClick :name="'MyButton'" />123</template>
import { getCurrentInstance, ref } from 'vue'export default {props: {name: String},setup(props,ctx) {let info = ref(0);const ins = getCurrentInstance();console.log("props.name",props.name)return {info, handleClick, secondClick, thirdClick}}}

– 第二个参数:context
和props一样的用法, 但是不写也可以用,context参数是一个普通的javascript对象,它对组件暴露三个属性:attrs、slots、emit。
attrs和slots是有状态的对象,它们总是会随组件本身的更新而更新。这意味着你应该避免对它们进行解构,并始终以attrs.x或slots.x的方式引用property。attrs和slots是非响应式的。应该在onUpdated生命周期钩子中执行此操作。

attrs:当父组件传递数据给子组件时,子组件不通过props接收,那么父组件传递的数据就到了 setup中的context的attrs属性。
slots:用于接收渲染父组件传递的插槽内容。
emit:向父组件触发事件。