• Vue3 setup中使用生命周期函数


    setup简单介绍

    setup是组合Composition API中的入口函数,也是第一个要使用的函数。setup只在初始化时执行一次,所有的Composition API函数都在此使用。Composition API代码组织很灵活,代码直接全部都写在setup里面即可(简单点来说,就是vue2⾥⾯的data,method,computed···全不要啦,所有数据⽅法全写在setup⾥
    在这里插入图片描述

    可以推断出setup执行的时候,组件对象还没有创建,组件实例对象this还不可用,此时this是undefined, 不能通过this来访问data/computed/methods/props

    1. setup函数执行于beforeCreate和created之前,也就是说setup函数里面无法使用data和methods方法中的数据
    2. setup 有2个参数
        props 的父组件传递过来的参数
        ctx 上下文对象
            ctx.attrs
            ctx.slots
            ctx.parent
            ctx.root
            ctx.emit
            ctx.refs
    3.在 setup() 函数中无法访问到 this
    4. 在setup函数中定义的变量和方法最后都是需要 return 出去的 不然无法再模板中使用
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    setup标签

    <script setup name="Dict">
    	1. name 表示组件的名称
    	2. 访问props 使用defineProps
     	const props = defineProps({
    	    //子组件接收父组件传递过来的值
    	    info:{
    	        type: Object
    	    }
    	})
    	3. ctx.emit 触发事件=》defineEmit(['selected']) // 传递值
    	4. ctx.expose 暴露公共 函数 =》defineExpose({函数名称});
    	
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    使用时要注意vue3版本,3.2开始支持,更简洁。定义的变量和方法都是不需要 return 出去的 就能模板中使用

    响应式数据

    1. 简单数据类型(String、Number, bool 等)推荐使⽤ref
    引入 import {ref} from 'vue'
    使用: let num = ref(1)
    获取/修改值:num.value
    2. 复杂数据类型(Array、Object)推荐使⽤reactive
     import {reactive} from 'vue'
     let arr = reactive({age:1}) 传⼊⼀个对象,vue会封装成Proxy对象,使⽤⾥⾯的⽅法实现响应式数据
     直接修改数据: arr.age = 12
     3. toRef():当我们在模板中渲染数据时,不希望由前缀的时候可以使用组合-toRef()
     toRef()是函数,转换响应式对象中某个属性为单独响应式数据,并且值是关联的
     	//  数据响应式:
        const obj = reactive({
          msg: 'hello',
          info: 'hi'
        })
        const msg = toRef(obj, 'msg')
        const info = toRef(obj, 'info')
        const hClick = () => {
          msg.value = 'nihao'
          info.value= 'hihi'
        }
      可以直接访问: msg, info
     4. toRefs():toRefs函数可以定义转换响应式中所有属性为 响应式数据,通常用于结构reactive定义的对象,转换响应式对象中所有属性(也可以是一部分)为单独响应式数据,对象成为普通对象,并且值是关联的
    const { msg, info } = toRefs(obj);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    注意:如果不需要做响应式的数据,直接声明变量即可。⽐如从接⼝获取的数据,

    生命周期

    生命周期函数有:onBeforeMount、onMounted、onBeforeUpdate、onUpdated、onBeforeUnmount、onUnmounted、onErrorCaptured、onRenderTracked、 onRenderTriggered、onActivated、onDeactivated。
    与vue2不同,vue3在vue2的生命周期的名字的基础上加了个on

    script>
    import {
      onBeforeMount,
      onMounted,
      onBeforeUpdate,
      onUpdated,
      onBeforeUnmount,
      onUnmounted,
      onRenderTracked,
      onRenderTriggered,
    } from "vue";
    export default {
      components: {},
      data() {
        return {};
      },
      setup() {
        // setup里面存着两个生命周期创建前创建
        // beforeCreate
        // created
        onBeforeMount(() => {
          console.log("onBefore   ====>  vue2.0 x beforemount");
        });
        onMounted(() => {
          console.log("onMounted  ====>  vue2.0 x mount");
        });
        onBeforeUpdate(() => {
          console.log("onBeforeUpdate  ====>  vue2.0 x beforeUpdate");
        });
        onUpdated(() => {
          console.log("onUpdated  ====>  vue2.0 x update");
        });
        onBeforeUnmount(() => {
          //在卸载组件实例之前调用。在这个阶段,实例仍然是完全正常的。
          console.log("onBeforeUnmount ====>  vue2.0 x beforeDestroy");
        });
        onUnmounted(() => {
          //卸载组件实例后调用,调用此钩子时,组件实例的所有指令都被解除绑定,所有事件侦听器都被移除,所有子组件实例被卸载。
          console.log("onUnmounted ====>  vue2.0 x destroyed");
        });
        // 新增两个生命周期函数
        //每次渲染后重新收集响应式依赖
        onRenderTracked(({ key, target, type }) => {
          // 跟踪虚拟DOM重新渲染时调用,钩子接收debugger event作为参数,此事件告诉你哪个操作跟踪了组件以及该操作的目标对象和键。
          // type:set/get操作
          // key:追踪的键
          // target:重新渲染后的键
          console.log("onRenderTracked");
        });
        //每次触发页面重新渲染时自动执行
        onRenderTriggered(({ key, target, type }) => {
          //当虚拟DOM重新渲染被触发时调用,和renderTracked类似,接收debugger event作为参数,
          // 此事件告诉你是什么操作触发了重新渲染,以及该操作的目标对象和键
          console.log("onRenderTriggered");
        });
        return {};
      },
    };
    </script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59

    在setup中执行生命周期和外部的生命周期函数相比,会优先指向setUp内的生命周期函数,再去执行外部的生命周期函数

    父子组件生命周期

    父组件:

    <template>
    <div class="container">
     父组件-->{{msg}}
     //子组件
    <ChildItem :msg="msg" :msg1="msg1"></ChildItem>
    </div>
    </template>
    
    
    <script lang="ts">
    import { defineComponent,ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated } from 'vue'
    import ChildItem from './components/base/Child.vue'
    export default defineComponent({
      name: 'App',
      components: {
        ChildItem
    
      },
      beforeCreate () {
        console.log('父beforeCreate')
      },
      created () {
        console.log('父created')
      },
      setup () {
        console.log('父setup')
        onBeforeMount(() => {
          console.log('父onBeforeMount')
        })
        onMounted(() => {
        //更新数据
        setTimeout(() => {
            msg.value = 'hello,1s后修改msg'
            console.log('msg 被修改')
          }, 1000)
          console.log('父onMounted')
        })
        onBeforeUpdate(() => {
          console.log('父onBeforeUpdate')
        })
        onUpdated(() => {
          console.log('父onUpdated')
        })
      }
    })
    </script>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    Child.vue

    <template>
      <div>子组件-->{{msg}}</div>
    
    </template>
    
    <script lang="ts">
    import { defineComponent, onBeforeMount, onMounted, onBeforeUpdate, onUpdated } from 'vue'
    
    export default defineComponent({
      name: 'ChildItem',
      props: {
        msg: {
          type: String,
          required: true
        }
      },
      beforeCreate () {
        console.log('子beforeCreate')
      },
      created () {
        console.log('子created')
      },
      setup (props, { attrs, slots, emit }) {
        console.log('子setup')
        onBeforeMount(() => {
          console.log('子onBeforeMount')
        })
        onMounted(() => {
          console.log('子onMounted')
        })
        onBeforeUpdate(() => {
          console.log('子onBeforeUpdate')
        })
        onUpdated(() => {
          console.log('子onUpdated')
        })
      }
    
    })
    </script>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    在这里插入图片描述

  • 相关阅读:
    MySQL的卸载
    R语言:利用biomod2进行生态位建模
    Windows 10 读取bitlocker加密的硬盘出现参数错误怎么解决?
    大聪明教你学Java | Mysql 为何会引起锁表及其解决办法
    4.Docker 搭建 redis6
    Leetcode 101. 对称二叉树
    【SpringBoot系列教程-目录大纲】
    Vue3.2弹窗表单多功能组件的封装
    Linux网络配置,常用命令及远程工具
    vue3项目到React 的nextjs项目的改版升级后,网站不更新,如何清理缓存,让改版后的网站生效?
  • 原文地址:https://blog.csdn.net/gao_xu_520/article/details/125559272