Vue3 生命周期 && Hooks封装 && toRef

2022-10-15,,,,

  1 # 一、Vue3.0与Vue2.0生命周期改动
2 beforDestroy改名为beforeUnmount
3 destroyed改名为unmounted
4 # Vue3.0页提供了Composition API形式的生命周期钩子,与Vue2.x中猴子对应关系如下:
5 import {onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted} from 'vue'
6 beforeCreate ====> setup()
7 created ====> setup()
8 beforeMount ====> onBeforeMount
9 mounted ====> onMounted
10 beforeUpdate ====> onBeforeUpdate
11 updated ====> onUpdated
12 beforeUnmount ====> onBeforeUnmount
13 unmounted ====> onUnmounted
14 # 注意:
15 # 1.setup函数中如何编写生命周期钩子:setup(){onBeforeMount(()=>{console.log('onBeforeMount被调用了!');})}
16 # 2.你可以直接通过配置项去配置生命周期(也就是不通过setup中Composition API的形式编码生命周期回调,直接和Vue2.x中一样配置)
17 # 3.当你setup中编写了生命周期回调,同时配置项中也配置了生命周期函数的时候,Vue3.0是默认先调用Composition API的形式编码生命周期回调,然后在调用配置项中的生命周期回调。
18 # 二、自定义hook函数
19 # 1.什么是hook函数? —— 本质是一个函数,把setup函数中使用的Composition API进行了封装
20 # 2.类似于Vue2.x中的mixin混入。
21 # 3.自定义hook的有事:复用代码,让setup中的逻辑更清楚易懂。
22 # 举个例子:
23 # /hooks/usePoint.js 把单独的功能或业务独立封装一个文件
24 import {reactive, onBeforeUnmount, onMounted} from 'vue'
25
26 export default function (){
27 let mPoint = reactive({
28 x: 0,
29 y: 0
30 })
31 function savePoint(event){
32 mPoint.x = event.pageX;
33 mPoint.y = event.pageY;
34 console.log('savePoint');
35 }
36 onMounted(()=>{
37 console.log('onMounted');
38 window.addEventListener('click', savePoint);
39
40 });
41 onBeforeUnmount(()=>{
42 console.log('onBeforeUnmount');
43 window.removeEventListener('click', savePoint);
44 });
45 return mPoint;
46 }
47 # Demo.vue
48 <template>
49 <h2>sum的值:{{sum}}</h2>
50 <button @click="sum+=1">点我+1</button>
51 <hr>
52 <div>鼠标点击的坐标是:({{mPoint.x}},{{mPoint.y}})</div>
53 </template>
54
55 <script>
56 import {ref} from 'vue'
57 import savePoint from '../hooks/usePoint.js' // 引入封装好的功能
58 export default {
59 name: 'HelloWorld',
60 setup(props, context){
61 let sum = ref(0);
62 let mPoint = savePoint(); // 然后安装功能
63 return {
64 sum,
65 mPoint // 暴露它,你就可以显示在页面上了
66 }
67 }
68 }
69 </script>
70 # 三、toRef函数
71 # 1.作用:创建一个ref对象,其value值指向另一个对象中的某个属性
72 # 2.语法:const name = toRef(pserson, 'name')
73 # 3.应用:要将响应式对象中的某个属性单独提供给外部使用时。
74 # 4.扩展:toRefs与toRef功能一直,但可以批量创建多个ref对象,语法:toRefs(person)
75 # 例子:
76 <template>
77 <h3>姓名:{{name}}</h3>
78 <h3>年龄{{age}}</h3>
79 <h3>薪资:{{job.j1.salary}}K</h3>
80 <button @click="name+='~'">修改姓名</button>
81 <button @click="age++">年龄增长</button>
82 <button @click="salary++">涨薪</button>
83 </template>
84
85 <script>
86 import {reactive, toRef, toRefs} from 'vue'
87 export default {
88 name: 'HelloWorld',
89 setup(props, context){
90 let person = reactive({
91 name: '张三',
92 age: 18,
93 job:{
94 j1:{
95 salary: 30
96 }
97 }
98 });
99
100 return {
101 salary: toRef(person.job.j1, 'salary'),
102 ...toRefs(person)
103 }
104 }
105 }
106 </script>

Vue3 生命周期 && Hooks封装 && toRef的相关教程结束。

《Vue3 生命周期 && Hooks封装 && toRef.doc》

下载本文的Word格式文档,以方便收藏与打印。