Vue3 Day5-Vue3的生命周期

news2024/9/19 7:56:25

5.1 Vue3的生命周期

vue2                 vue3
beforeCreate        setup()
created             setup()
beforeMount         onBeforeMount
mounted             onMounted
beforeUpdate        onBeforeUpdate
updated             onUpdated
beforeDestroy       onBeforeUnmount
destroyed           onUnmounted
activated            onActivated
deactivated          onDeactivated
非语法糖生命周期写法

父组件 App.vue

<template>
    <div>
        <button @click="type='tab1'">显示tab1</button>
        <button @click="type='tab2'">显示tab2</button>
        <!-- 动态组件 -->
        <keep-alive>
            <component :is="type"></component>
        </keep-alive>
        <!-- 子组件 -->
        <HelloWorld v-if="show"></HelloWorld>
        <button @click="isShow">显示吗</button>
    </div>
</template>
​
<script>
    import tab1 from './components/tab1.vue'
    import tab2 from './components/tab2.vue'
    import HelloWorld from './components/HelloWorld.vue'
​
    import {
        ref
    } from 'vue'
​
    export default {
        components: {
            tab1,
            tab2,
            HelloWorld
        },
        beforeCreate() {
            console.log('beforeCreate');
        },
        created() {
            console.log('created');
        },
        beforeMount() {
            console.log('beforeMount');
        },
        mounted() {
            console.log('mounted');
        },
        beforeUpdate() {
            console.log('beforeUpdate');
        },
        updated() {
            console.log('updated');
        },
        activated() {
            console.log('activated');
        },
        deactivated() {
            console.log('deactivated');
        },
        beforeUnmount() {
            console.log('beforeUnmount');
        },
        unmounted() {
            console.log('unmounted');
        },
        setup() {
            let type = ref('tab1')
            // 子组件:探讨父子组件生命周期执行顺序
            let show = ref(true)
            let isShow = () => {
                show.value = !show.value
            }
            return {
                type,
                show,
                isShow
            }
        }
    }
</script>
​
<style scoped>
​
</style>

子组件

HelloWorld.vue

<template>
    <div>子组件</div>
</template>
​
<!-- setup取代了export default -->
<script>
    import {
        ref,
        reactive
    } from 'vue'
​
    export default {
        beforeCreate() {
            console.log('子beforeCreate');
        },
        created() {
            console.log('子created')
        },
        beforeMount() {
            console.log('子beforeMount');
        },
        mounted() {
            console.log('子mounted')
        },
        beforeUpdate() {
            console.log('子beforeUpdate');
        },
        updated() {
            console.log('子updated');
        },
        activated() {
            console.log('子activated');
        },
        deactivated() {
            console.log('子deactivated');
        },
        beforeUnmount() {
            console.log('子组件beforeUnmount');
        },
        unmounted() {
            console.log('子组件unmounted');
        }
    }
</script>
​
<style scoped>
    div {
        color: #aa0000;
    }
</style>

tab1.vue

<template>
    <div>我是tab1</div>
</template>
​
<!-- setup取代了export default -->
<script>
​
</script>
​
<style scoped>
    div {
        color: #f60;
    }
</style>

tab2.vue

<template>
    <div>我是tab2</div>
</template>
​
<!-- setup取代了export default -->
<script>
​
</script>
​
<style scoped>
    div {
        color: #f60;
    }
</style>
语法糖生命周期写法

父组件 App.vue

<template>
    <div>
        <button @click="tab11">显示tab1</button>
        <button @click="tab22">显示tab2</button>
        <!-- 动态组件 -->
        <keep-alive>
            <component :is="type"></component>
        </keep-alive>
        <!-- 子组件 -->
        <HelloWorld v-if="show"></HelloWorld>
        <button @click="isShow">显示吗</button>
    </div>
</template>
​
<script setup>
    import tab1 from './components/tab1.vue'
    import tab2 from './components/tab2.vue'
​
    import HelloWorld from './components/HelloWorld.vue'
​
    import {
        ref,
        onBeforeMount,
        onMounted,
        onBeforeUpdate,
        onUpdated,
        onBeforeUnmount,
        onUnmounted
    } from 'vue'
​
    // vue3 注册动态组件用defineOptions()
    defineOptions({
        components: {
            tab1,
            tab2
        }
    })
    onBeforeMount(() => {
        console.log('onBeforeMount');
    })
    onMounted(() => {
        console.log('onMounted');
    })
    onBeforeUpdate(() => {
        console.log('onBeforeUpdate');
    })
    onUpdated(() => {
        console.log('onUpdated');
    })
    onBeforeUnmount(() => {
        console.log('onBeforeUnmount');
    })
    onUnmounted(() => {
        console.log('onUnmounted');
    })
​
    let type = ref('tab1')
    let tab11 = () => {
        type.value = 'tab1'
    }
    let tab22 = () => {
        type.value = 'tab2'
    }
    // 子组件:探讨父子组件生命周期执行顺序
    let show = ref(true)
    let isShow = () => {
        show.value = !show.value
    }
    // vue3 父子组件生命周期执行顺序
    // 父setup-父beforeCreated-父created-父beforeMounted-子beforeCreate-子Create-子beforeMount-父activated-子mounted-父mounted
    //在setup语法糖情况下 没有beforeCreate 和created这两个生命周期 
</script>
​
<style scoped>
​
</style>

子组件

HelloWorld.vue

<template>
    <div>子组件</div>
</template>
​
<!-- setup取代了export default -->
<script setup>
    import {
        onBeforeMount,
        onMounted,
        onBeforeUpdate,
        onUpdated,
        onBeforeUnmount,
        onUnmounted
    } from 'vue'
​
    onBeforeMount(() => {
        console.log('子onBeforeMount');
    })
    onMounted(() => {
        console.log('子onMounted');
    })
    onBeforeUpdate(() => {
        console.log('子onBeforeUpdate');
    })
    onUpdated(() => {
        console.log('子onUpdated');
    })
    onBeforeUnmount(() => {
        console.log('子onBeforeUnmount');
    })
    onUnmounted(() => {
        console.log('子onUnmounted');
    })
</script>
​
<style scoped>
    div {
        color: #aa0000;
    }
</style>

tab1.vue

<template>
    <div>我是tab1</div>
</template>
​
<!-- setup取代了export default -->
<script setup>
    import {
        onActivated,
        onDeactivated
    } from 'vue'
​
    onActivated(() => {
        console.log('tab1-onActivated');
    })
    onDeactivated(() => {
        console.log('tab1-onDeactivated');
    })
</script>
​
<style scoped>
    div {
        color: #f60;
    }
</style>

tab2.vue

<template>
    <div>我是tab2</div>
</template>
​
<!-- setup取代了export default -->
<script setup>
    import {
        onActivated,
        onDeactivated
    } from 'vue'
​
    onActivated(() => {
        console.log('tab2-onActivated');
    })
    onDeactivated(() => {
        console.log('tab2-onDeactivated');
    })
</script>
​
<style scoped>
    div {
        color: #f60;
    }
</style>

5.2 hooks函数

App.vue

<template>
    <div>
        <h1>屏幕尺寸</h1>
        <div>宽度:{{width}}</div>
        <div>高度:{{height}}</div>
    </div>
</template>
​
<script setup>
    import {
        ref,
        onMounted
    } from 'vue'
    import useWindowResize from './hooks/useWindowResize.js'
    let {
        width,
        height
    } = useWindowResize()
    onMounted(() => {
        document.title = 'hooks函数'
    })
</script>
​
<style scoped>
​
</style>

hooks->useWindowResize.js

js文件名字必须以 use开头

import {
    ref,
    onMounted
} from 'vue'
​
// 封装的hooks的js文件名必须以 ‘use’开头
function useWindowResize() {
    let width = ref(0)
    let height = ref(0)
    let onResize = () => {
        width.value = window.innerWidth
        height.value = window.innerHeight
    }
​
    onMounted(() => {
        // 方法onResize 挂载时不用加括号
        window.addEventListener('resize', onResize)
        onResize()
    })
​
    return {
        width,
        height
    }
}
export default useWindowResize

5.3 toRef()的使用

非语法糖

<template>
    <div>
        <h2>{{name}}</h2>
        <h2>{{age}}</h2>
        <button @click="change">改变吧</button>
    </div>
</template>
​
<script>
    import {
        reactive,
        toRef
    } from 'vue'
    export default {
        setup() {
            let person = reactive({
                name: 'king',
                num1: {
                    num2: {
                        age: 12
                    }
                }
            })
            // toRef可以基于响应式对象上的一个属性,创建一个对应的 ref,这样创建的 ref 与其源属性保持同步:改变源属性的值将更新 ref 的值,反之亦然。
            let name = toRef(person, 'name')
            let age = toRef(person.num1.num2, 'age')
​
            let change = () => {
                name.value += '@'
                age.value++
            }
            return {
                person,
                name,
                age,
                change
            }
        }
    }
</script>
​
<style scoped>
​
</style>

语法糖

<template>
    <div>
        <h2>{{name}}</h2>
        <h2>{{age}}</h2>
        <button @click="change">改变吧</button>
    </div>
</template>
​
<script setup>
    import {
        reactive,
        toRef
    } from 'vue'
​
    let person = reactive({
        name: 'king',
        num1: {
            num2: {
                age: 12
            }
        }
    })
    // toRef可以基于响应式对象上的一个属性,创建一个对应的 ref,这样创建的 ref 与其源属性保持同步:改变源属性的值将更新 ref 的值,反之亦然。
    let name = toRef(person, 'name')
    let age = toRef(person.num1.num2, 'age')
​
    let change = () => {
        name.value += '@'
        age.value++
    }
</script>
​
<style scoped>
​
</style>

5.4 toRefs()的使用

<template>
    <div>
        <h2>{{name}}</h2>
        <h2>{{age}}</h2>
        <h2>{{school}}</h2>
        <button @click="change">改变吧</button>
    </div>
</template>
​
<script setup>
    import {
        ref,
        reactive,
        toRef,
        toRefs
    } from 'vue'
​
    let person = reactive({
        name: 'king',
        school: '观音大士学府',
        num1: {
            num2: {
                age: 12
            }
        }
    })
    // toRefs只能解构一层,多层级需要在toRefs中包裹多层例如:let {sex} = toRefs(person.job.j1)
    let {
        name,
        school
    } = toRefs(person)
    let {
        age
    } = toRefs(person.num1.num2)
​
    let change = () => {
        name.value += '@'
        age.value++
    }
​
    // 错误做法:
    // 这里不能用ref来取代toRef 因为ref定义的数据已经和原数据不是一个数据了,即非同源
    // let name = ref(person.name)
    // console.log(name); //king
</script>
​
<style scoped>
​
</style>

5.5 shallowReactive与shallowRef

<template>
    <div>
        <!-- <h2>{{name}}</h2> -->
        <h2>{{person.age}}</h2>
        <h2>{{person.work.job.num}}</h2>
        <button @click="change">改变吧</button>
    </div>
</template>
​
<script setup>
    import {
        shallowRef,
        shallowReactive
    } from 'vue'
​
    // shallowRef:只处理基本数据类型的响应式, 不进行对象的响应式处理
    // let name = shallowRef('king')
    // let person = shallowRef({
    //  age: 12,
    //  work: {
    //      job: {
    //          num: 1
    //      }
    //  }
    // })
    // let change = () => {
    //  name.value += '@'
    //  // 如果shallowRef非要处理对象的,可以使用以下方法
    //  person.value = {
    //      age: 16
    //  }
    // }
​
    // shallowReactive:只处理对象最外层属性的响应式(浅响应式)
    let person = shallowReactive({
        age: 12,
        work: {
            job: {
                num: 1
            }
        }
    })
    let change = () => {
        // 产生响应式
        // person.age++
​
        // 不产生响应式
        person.work.job.num++
        console.log(person.work.job.num);
    }
</script>
​
<style scoped>
​
</style>

5.6 readonly与shallowReadonly

<template>
    <div>
        <h2>{{person.age}}</h2>
        <h2>{{person.work.job.num}}</h2>
        <button @click="change">改变吧</button>
    </div>
</template>
​
<script setup>
    import {
        shallowRef,
        shallowReactive,
        readonly,
        shallowReadonly
    } from 'vue'
​
​
    // shallowReadonly:让一个响应式数据变为只读的(浅只读)
    // let person = shallowReadonly({
    //  age: 12,
    //  work: {
    //      job: {
    //          num: 1
    //      }
    //  }
    // })
    // let change = () => {
    //  person.age++ //只读
    // }
​
​
    // readonly: 让一个响应式数据变为只读的(深只读)
    let person = shallowReadonly({
        age: 12,
        work: {
            job: {
                num: 1
            }
        }
    })
    let change = () => {
        person.work.job.num++ //只读
        console.log(111);
    }
</script>
​
<style scoped>
​
</style>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2141540.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Redis基础数据结构之 ziplist 压缩列表 源码解读

目录标题 ziplist 是什么?ziplist 特点ziplist 数据结构ziplist 节点pre_entry_lengthencoding 和 lengthcontent ziplist 基本操作插入&#xff08;Insertion&#xff09;删除&#xff08;Deletion&#xff09;查找&#xff08;Search&#xff09;更新&#xff08;Update&…

Qt多元素控件——QTableWidget

文章目录 QTabWidget核心属性、方法和信号使用示例 QTabWidget核心属性、方法和信号 QTableWidget表示一个表格控件&#xff0c;一个表格中包含若干行&#xff0c;每一行包含若干列。 表格中的每一个单元格&#xff0c;是一个QTableWidgetItem对象。 QTableWidget核心方法&a…

Java 每日一刊(第9期):数组

文章目录 前言什么是数组初始化数组如何访问和操作数组遍历数组多维数组数组的常见操作复制数组排序数组搜索数组 数组的长度和异常处理Arrays 工具类本期小知识 “简单是效率的灵魂。” 前言 这里是分享 Java 相关内容的专刊&#xff0c;每日一更。 本期将为大家带来以下内…

云计算和虚拟化技术 背诵

https://zhuanlan.zhihu.com/p/612215164 https://zhuanlan.zhihu.com/p/612215164 云计算是指把计算资源、存储资源、网络资源、应用软件等集合起来&#xff0c;采用虚拟化技术 &#xff0c;将这些资源池化&#xff0c;组成资源共享池&#xff0c;共享池即是“云”。 云计算…

从零开始学习Linux(12)---进程间通信(信号量与信号)

1.信号量 信号量是计算机科学中用于同步和互斥的一种抽象数据类型。在并发编程中&#xff0c;当多个进程或线程需要访问共享资源时&#xff0c;信号量用来确保资源在同一时刻只被一个进程或线程访问&#xff0c;从而避免竞争条件。 信号量通常具有以下特性&#xff1a; 整…

Fisco Bcos 2.11.0配置console控制台2.10.0及部署调用智能合约

Fisco Bcos 2.11.0配置console控制台2.10.0及部署调用智能合约 文章目录 Fisco Bcos 2.11.0配置console控制台2.10.0及部署调用智能合约前言版本适配一、启动FIsco Bcos区块链网络二、获取控制台文件三、配置控制台3.1 执行download_console.sh脚本3.2 拷贝控制台配置文件3.3 修…

读构建可扩展分布式系统:方法与实践06异步消息传递

1. 异步消息传递 1.1. 通信是分布式系统的基础&#xff0c;也是架构师需要纳入其系统设计的主要问题 1.2. 客户端发送请求并等待服务器响应 1.2.1. 这就是大多数分布式通信的设计方式&#xff0c;因为客户端需要得到即时响应后才能继续 1.2.2. 并非所有系统都有这个要求 1…

数据时代,职场离不开的远程控制工具

中秋了大概率是在正常放假了吧&#xff0c;如果突发遇到需要你处理的文件怎么办呢&#xff1f;其实有远程操作工具你就不用到办公室了。向日葵远程控制软件这些工具就可以帮我们远程实现控制电脑操作。如果你也有这方面需求就继续看吧&#xff0c;这次我将介绍几款我用过效果比…

Redis常见应用场景

目录 一、实现博客点赞功能 二、实现博客点赞用户列表功能 三、好友关注和取关以及求共同关注 四、实现关注推送 1、拉模式 2、推模式 3、推拉结合 四、三种模式对比 这里简单记录一下&#xff0c;没有实现方法&#xff0c;只是帮助记忆 一、实现博客点赞功能 可以通…

[NSSRound#4 SWPU]hide_and_seek-用gdb调试

看反汇编 ; __unwind { .text:0000000000001514 F3 0F 1E FA endbr64 .text:0000000000001518 55 push rbp .text:0000000000001519 48 89 E5 mov rbp, rsp .text:000000000000151C 53 …

python tkinter

基本使用 基于tkinter创建 GUI基本四步&#xff1a;窗口->组件->布局->事件 1.创建窗口对象 from tkinter import *root Tk() # 创建窗口root.mainloop() # 进入事件循环 2.创建组件 按钮文本等组件 btn Button(root) # 创建Button组件&#xff0c;使组件在…

re题(25)BUUFCTF-[GUET-CTF2019]re

BUUCTF在线评测 (buuoj.cn) 查下壳&#xff0c;是upx壳 脱一下 查看字符串&#xff0c;定位到主函数&#xff0c;也可以用ctrlE的方式找到主函数 明显&#xff0c;sub_4009AE是对flag加密的关键函数 进入sub_4009AE看一下 看到这儿有一堆大数和方程&#xff0c;我们知道要用z…

Transformer模型详细步骤

Transformer模型是nlp任务中不能绕开的学习任务&#xff0c;我将从数据开始&#xff0c;每一步骤都列举出来&#xff0c;然后对应重点的代码进行讲解 ------------------------------------------------------------------------------------------------------------- Trans…

Skytower

一、安装配置靶机 下载地址: SkyTower: 1 ~ VulnHub 下载之后解压发现是VirtualBox格式的 我们下载一个VirtualBox&#xff0c;这是官网 Downloads – Oracle VirtualBox 安装到默认路径就 打开后点击注册 选择解压后的vbox文件 然后点击左上角管理 点击导出虚拟电脑&…

PCIe进阶之TL:Request Handling Rules

1 Handling of Received TLPs 本节介绍接收到的 TLP 在数据链路层经过完整性验证之后,这些 TLP 在事务处理层时的处理方式。这些规则如下图所示: 接收侧会忽略保留字段。如果 Fmt 字段显示存在至少一个 TLP Prefix : (1)通过检查后续 DWORD 的第一个字节中的 Fmt 字段,…

两个人群填充参考(CHN100K和NARD)

分别是中国人群和东北亚人群的填充参考&#xff0c;测试了下&#xff0c;中国人群的参考注册还是相对友好的&#xff0c;没有像有些网站一样严格限制。东北亚的没有测试&#xff0c;两个数据库的特点都是包含了少数民族&#xff0c;研究朝鲜或蒙古族或其他民族的同学&#xff0…

Java 枚举 新特性

Java 枚举&#xff08;enum&#xff09;自JDK 1.5引入以来&#xff0c;随着版本的升级不断增强。本文将回顾枚举的演进&#xff0c;尤其是结合switch语句的应用&#xff0c;展示枚举如何在现代Java中变得更加灵活。 1. JDK 1.5&#xff1a;Java 枚举的诞生 在JDK 1.5之前&…

Dbt基本概念与快速入门

在过去的几年里&#xff0c;数据科学界已经慢慢地接受了以数据为中心的范式。我们不仅关注日益复杂的机器学习模型&#xff0c;还要更多地关注数据质量。这使得数据工程、分析工程领域技术和工具成为热点。dbt(数据构建工具)是一个显著改善数据工程师生活的工具。它的目的是向数…

【漏洞复现】金某云星空ERP GetImportOutData .net反序列化漏洞

免责声明&#xff1a; 本文内容旨在提供有关特定漏洞或安全漏洞的信息&#xff0c;以帮助用户更好地了解可能存在的风险。公布此类信息的目的在于促进网络安全意识和技术进步&#xff0c;并非出于任何恶意目的。阅读者应该明白&#xff0c;在利用本文提到的漏洞信息或进行相关测…

Chinese Spelling Correction as Rephrasing Language Model(AAAI2024)

Chinese Spelling Correction as Rephrasing Language Model(AAAI2024) 一&#xff0e;概述 目前最先进的方法将CSC(Chinese Spelling Correction)作为序列标注任务&#xff0c;并在句子对上微调基于bert的方法。然而&#xff0c;我们注意到在将一个字符标注为另一个字符的过…