发布时间:2025-06-24 17:51:54 作者:北方职教升学中心 阅读量:388
添加事件监听 const handler = () => console.log('window resize') window.addEventListener('resize', handler) // 清理工作 onUnmounted(() => { window.removeEventListener('resize', handler) })})// 更新前onBeforeUpdate(() => { console.log('Component is about to update') // 可以访问更新前的 DOM})// 更新后onUpdated(() => { console.log('Component is updated') // 可以访问更新后的 DOM})// 卸载前onBeforeUnmount(() => { console.log('Component is about to unmount') // 适合进行最终的清理工作})// 实际应用示例const fetchData = async () => { try { const response = await fetch('/api/data') data.value = await response.json() } catch (error) { console.error(error) }}onMounted(async () => { await fetchData() // 设置定时刷新 const timer = setInterval(fetchData, 60000) onUnmounted(() => { clearInterval(timer) })})</script>
3.4 自定义 Hooks
重点掌握:
- Hook 的封装原则
- 复用逻辑的最佳实践
- 响应式数据的处理
示例代码:
// useCounter.tsimport{ref,computed }from'vue'exportfunctionuseCounter(initialValue =0){constcount =ref(initialValue)constdouble =computed(()=>count.value *2)constincrement=()=>count.value++constdecrement=()=>count.value--constreset=()=>count.value =initialValue return{count,double,increment,decrement,reset }}// useAsyncData.tsimport{ref }from'vue'exportfunctionuseAsyncData(fetchFunction){constdata =ref(null)consterror =ref(null)constloading =ref(false)constfetch=async()=>{loading.value =trueerror.value =nulltry{data.value =awaitfetchFunction()}catch(err){error.value =err }finally{loading.value =false}}return{data,error,loading,fetch }}// 使用示例<script setup>import{useCounter,useAsyncData }from'./hooks'// 使用计数器const{count,double,increment }=useCounter(10)// 使用异步数据const{data,error,loading,fetch }=useAsyncData(()=>fetch('/api/users').then(r =>r.json()))// 组合多个 hooksconstuseUserCounter=()=>{const{users }=useAsyncData(()=>fetch('/api/users'))const{count,increment }=useCounter()return{users,count,increment }}</script>
3.5 路由基础
重点掌握:
- Vue Router 的基本配置
- 路由导航方式
- 路由守卫使用
示例代码:
// router/index.tsimport{createRouter,createWebHistory }from'vue-router'constrouter =createRouter({history:createWebHistory(),routes:[{path:'/',name:'Home',component:()=>import('../views/Home.vue')},{path:'/about',name:'About',component:()=>import('../views/About.vue')},{path:'/user/:id',name:'User',component:()=>import('../views/User.vue'),props:true,// 路由独享守卫beforeEnter:(to,from)=>{// 验证逻辑}}]})// 全局前置守卫router.beforeEach((to,from)=>{// 检查用户是否已登录if(to.meta.requiresAuth &&!isAuthenticated()){return{name:'Login'}}})exportdefaultrouter// App.vue<template><nav><RouterLink to="/">Home</RouterLink><RouterLink to="/about">About</RouterLink></nav><RouterView v-slot="{ Component }"><Transition name="fade"mode="out-in"><component :is="Component"/></Transition></RouterView></template>// 组件中使用<script setup>import{useRouter,useRoute }from'vue-router'constrouter =useRouter()constroute =useRoute()// 编程式导航constgoToUser=(userId)=>{router.push({name:'User',params:{id:userId }})}// 获取路由参数constuserId =route.params.id</script>