您现在的位置是:首页 >其他 >Vue3技术5之watchEffect函数、Vue3生命周期、自定义hook函数网站首页其他
Vue3技术5之watchEffect函数、Vue3生命周期、自定义hook函数
                简介Vue3技术5之watchEffect函数、Vue3生命周期、自定义hook函数            
            Vue3技术5
watchEffect函数
Demo.vue
<template>
  <h2>和为:{{sum}}</h2>
  <button @click="sum++">和+1</button>
  <hr>
  <h2>当前的信息为:{{msg}}</h2>
  <button @click="msg+='!'">修改信息</button>
  <hr>
  <h2>个人信息</h2>
  <h2>姓名:{{person.name}}</h2>
  <h2>年龄:{{person.age}}</h2>
  <h2>薪资:{{person.job.j1.salary}}K</h2>
  <button @click="person.name+='~'">修改信息</button>
  <button @click="person.age++">增加年龄</button>
  <button @click="person.job.j1.salary++">涨薪</button>
</template>
<script>
import {reactive, ref, watch,watchEffect} from 'vue'
export default {
    name: "Demo",
    setup(){
      //数据
      let sum=ref(0)
      let msg=ref('你好啊')
      let person=reactive({
        name:'张三',
        age:18,
        job:{
          j1:{
            salary:20
          }
        }
      })
      //监视
      /*watch(sum,(newValue,oldValue)=>{
        console.log("sum值发生了改变",newValue,oldValue)
      },{immediate:true})*/
      watchEffect(() => {
        const x1=sum.value
        const x2=person.job.j1.salary
        console.log('watchEffect所指定的回调执行了~'+x1+x2)
      })
      //返回一个对象(常用)
      return{
          sum,
          msg,
          person
      }
    },
}
</script>
<style scoped>
</style>

总结
- watch的套路是:既要指明监视的属性,也要指明监视的回调
- watchEffect的套路是:不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性
- watchEffect有点像computed
 (1)但computed注重的计算出来的值(回调函数的返回值),所以必须要写返回值
 (2)而watchEffect更注重的是过程(回调函数的函数体), 不用写返回值
//watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调
watchEffect(()=>{
	const x1=sum.value
	const x2=person.age
	console.log('watchEffect配置的回调执行了')
})
Vue3生命周期
- Vue2.x生命周期:
  
- Vue3生命周期:
  
Vue3生命周期测试
App.vue
<template>
  <button @click="toggle=!toggle">切换显示/隐藏</button>
  <Demo v-if="toggle"></Demo>
</template>
<script>
import {ref} from 'vue'
import Demo from "@/components/Demo";
export default {
  name: 'App',
  components: {Demo},
  setup(){
    const toggle=ref(true)
    return{toggle}
  },
}
</script>
Demo.vue
<template>
  <h2>当前求和为:{{sum}}</h2>
  <button @click="sum++">点我+1</button>
</template>
<script>
import { ref } from 'vue'
export default {
    name: "Demo",
    setup(){
      //数据
      let sum=ref(0)
      //返回一个对象(常用)
      return{
          sum
      }
    },
    //通过配置项形式使用生命周期钩子
    beforeCreate() {
      console.log("-------beforeCreate-----------")
    },
    created() {
      console.log("--------created----------")
    },
    beforeMount() {
      console.log("--------beforeMount----------")
    },
    mounted() {
      console.log("--------mounted----------")
    },
    beforeUpdate() {
      console.log("--------beforeUpdate----------")
    },
    updated() {
      console.log("--------updated----------")
    },
    beforeUnmount() {
      console.log("--------beforeUnmount----------")
    },
    unmounted() {
      console.log("--------unmounted----------")
    }
}
</script>
<style scoped>
</style>

组合式API使用生命周期钩子
Demo.vue
<template>
  <h2>当前求和为:{{sum}}</h2>
  <button @click="sum++">点我+1</button>
</template>
<script>
import { ref ,onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted} from 'vue'
export default {
    name: "Demo",
    setup(){
      console.log("--------setup----------")
      //数据
      let sum=ref(0)
      //通过组合API的形式去使用生命周期钩子
      onBeforeMount(() => {
         console.log("--------onBeforeMount----------")
      })
      onMounted(() => {
         console.log("--------onMounted----------")
      })
      onBeforeUpdate(() => {
         console.log("--------onBeforeUpdate----------")
      })
      onUpdated(() => {
         console.log("--------onUpdated----------")
      })
      onBeforeUnmount(() => {
         console.log("--------onBeforeUnmount----------")
      })
      onUnmounted(() => {
         console.log("--------onUnmounted----------")
      })
      //返回一个对象(常用)
      return{
          sum
      }
    },
    //通过配置项形式使用生命周期钩子
    /*beforeCreate() {
      console.log("-------beforeCreate-----------")
    },
    created() {
      console.log("--------created----------")
    },
    beforeMount() {
      console.log("--------beforeMount----------")
    },
    mounted() {
      console.log("--------mounted----------")
    },
    beforeUpdate() {
      console.log("--------beforeUpdate----------")
    },
    updated() {
      console.log("--------updated----------")
    },
    beforeUnmount() {
      console.log("--------beforeUnmount----------")
    },
    unmounted() {
      console.log("--------unmounted----------")
    }*/
}
</script>
<style scoped>
</style>

总结:
- Vue3.0中可以继续使用Vue2.x中的生命周期钩子,但有两个被更名
- beforeDestroy改名为beforeUnmount
- destroyed改名为unmounted
- Vue3.0也提供了Composition API 形式的生命周期钩子,与Vue2.x中钩子对应关系如下:
- beforeCreate===>setup()
- created===>setup()
- beforeMount===>onBeforeMount
- mounted===>onMounted
- beforeUpdate===>onBeforeUpdate
- updated===>onUpdated
- beforeUnmount===>onBeforeUnmount
- unmounted===>onUnmounted
自定义hook函数
- 什么是hook?——本质是一个函数,把setup函数中使用的Composition API进行了封装
- 类似于Vue2.x中的mixin
- 自定义hook的优势:复用代码,让setup中的逻辑更清楚易懂
获取鼠标的x,y
Demo.vue
<template>
  <h2>当前求和为:{{sum}}</h2>
  <button @click="sum++">点我+1</button>
  <hr>
  <h2>当前点击时,鼠标的坐标为,x:{{point.x}},y:{{point.y}}</h2>
</template>
<script>
import {ref, reactive, onMounted, onBeforeUnmount} from 'vue'
export default {
    name: "Demo",
    setup(){
      console.log("--------setup----------")
      //数据
      let sum=ref(0)
      let point=reactive({
        x:0,
        y:0
      })
      //方法
      function savePoint(event){
        point.x=event.pageX
        point.y=event.pageY
        console.log(event.pageX,event.pageY)
      }
      onMounted(()=>{
        window.addEventListener('click',savePoint)
      })
      onBeforeUnmount(() => {
         window.removeEventListener('click',savePoint)
      })
      //返回一个对象(常用)
      return{
          sum,
        point
      }
    },
}
</script>
<style scoped>
</style>

使用hook方式
文件目录

hooks/usePoint.js
import {onBeforeUnmount, onMounted, reactive} from "vue";
export default function (){
    //实现鼠标“打点”相关的数据
    let point=reactive({
        x:0,
        y:0
    })
    //实现鼠标“打点”相关的方法
    function savePoint(event){
        point.x=event.pageX
        point.y=event.pageY
        console.log("x,y",point.x,point.y)
    }
    //实现鼠标“打点”相关的生命周期钩子
    onMounted(()=>{
        window.addEventListener('click',savePoint)
    })
    onBeforeUnmount(()=>{
        window.removeEventListener('click',savePoint)
    })
    return point
}
App.vue
<template>
  <button @click="toggle=!toggle">切换显示/隐藏</button>
  <Demo v-if="toggle"></Demo>
  <hr>
  <Test v-if="toggle"></Test>
</template>
<script>
import {ref} from 'vue'
import Demo from "@/components/Demo";
import Test from "@/components/Test";
export default {
  name: 'App',
  components: {Demo,Test},
  setup(){
    const toggle=ref(true)
    return{toggle}
  },
}
</script>
Demo.vue
<template>
  <h2>当前求和为:{{sum}}</h2>
  <button @click="sum++">点我+1</button>
  <hr>
  <h2>当前点击时,鼠标的坐标为,x:{{point.x}},y:{{point.y}}</h2>
</template>
<script>
import {ref} from 'vue'
import usePoint from "@/hooks/usePoint";
export default {
    name: "Demo",
    setup(){
      console.log("--------setup----------")
      //数据
      let sum=ref(0)
      let point=usePoint()
      //返回一个对象(常用)
      return{
          sum,
          point
      }
    },
}
</script>
<style scoped>
</style>
Test.vue
<template>
<div>
  <h2>我是Test组件</h2>
  <h2>当前点击时,鼠标的坐标为,x:{{point.x}},y:{{point.y}}</h2>
</div>
</template>
<script>
import usePoint from "@/hooks/usePoint";
    export default {
        name: "Test",
      setup(){
          let point=usePoint()
        return{
            point
        }
      }
    }
</script>
<style scoped>
</style>

风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。
        
    
        
     
            




 U8W/U8W-Mini使用与常见问题解决
U8W/U8W-Mini使用与常见问题解决 QT多线程的5种用法,通过使用线程解决UI主界面的耗时操作代码,防止界面卡死。...
QT多线程的5种用法,通过使用线程解决UI主界面的耗时操作代码,防止界面卡死。... stm32使用HAL库配置串口中断收发数据(保姆级教程)
stm32使用HAL库配置串口中断收发数据(保姆级教程) 分享几个国内免费的ChatGPT镜像网址(亲测有效)
分享几个国内免费的ChatGPT镜像网址(亲测有效) Allegro16.6差分等长设置及走线总结
Allegro16.6差分等长设置及走线总结