一、生命周期
Vue3中可以继续使用Vue2中的生命周期钩子,但有两个被更名:
- beforeDestroy改名为beforeUnmount
- destroy改名为unmounted
Vue3也提供了组合式API形式的生命周期钩子,与Vue2中钩子对应关系如下:
- beforeCreate ===> setup()
- created ===> setup()
- beforeMount ===> onBeforeMount
- mounted ===> onMounted
- beforeUpdate ===> onBeforeUpdate
- updated ===> onUpdated
- beforeUnmount ===> onBeforeUnmount
- unmounted ===> onUnmounted
import {ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted} from 'vue'
setup(){
let sum = ref(20)
// 通过组合式API的形式去使用生命周期钩子
onBeforeMount(()=>{
console.log('---onBeforeMount---')
})
onMounted(()=>{
console.log('---onMounted---')
})
onBeforeUpdate(()=>{
console.log('---onBeforeUpdate---')
})
…………
}
二、自定义hook函数
- 什么是hook? —— 本质是一个函数,把setup函数中使用的Composition API进行了封装。
- 类似于vue2.x中mixin。
- 自定义hook的优势:复用代码,让setup中的逻辑更清楚易懂。
创建一个js文件,比如usePoint.js ,内容:
import {reactive, onMounted, onBeforeUnmount} from 'vue'
export default function(){
let point = reactive({
x:0,
y:0
})
// 获取鼠标点击坐标
function savePoint(event){
point.x = event.pageX
point.y = event.pageY
}
onMounted(()=>{
window.addEventListener('click', savePoint)
})
onBeforeUnmount(()=>{
window.removeEventListener('click', savePoint)
})
return point
}
在vue文件中引入userPoint.js文章来源:https://www.toymoban.com/news/detail-673305.html
<p>鼠标点击坐标 x:{{point.x}} y:{{point.y}}<p>
import usePoint from '/hook/usePoint.js'
setup(){
let point = usePoint()
return { point }
}
三、toRef
- 作用:创建一个ref对象,其value值指向另一个对象中的某个属性。
- 语法:const name = toRef(person, ‘name’)
return {
name: toRef(person,'name')
salary: toRef(person.job.j1, 'salary')
}
- 应用:要将响应式对象中的某个属性单独提供给外部使用时。
- 扩展:toRefs 与 toRef 功能一致,但可以批量创建多个ref对象,语法:toRefs(person)
// person中的salary属性用法
<p> {{ job.j1.salary }} </p>
return {
// 把person属性都拆开
...toRefs(person)
}
四、参考链接
[01] Vue3学习笔记(尚硅谷) 文章来源地址https://www.toymoban.com/news/detail-673305.html
到了这里,关于556、Vue 3 学习笔记 -【常用Composition API(五)】 2023.08.25的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!