vue3.0学习之路 6(生命周期 + 自定义hook函数 + toRef)

481 阅读1分钟

生命周期

Vue3.0中可以继续使用Vue2.x中的生命周期钩子,但有有两个被更名:

  • beforeDestroy改名为 beforeUnmount

  • destroyed改名为 unmounted Vue3.0也提供了 Composition API(组合式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中的逻辑更清楚易懂。
    实现鼠标打点
    import {onBeforeUnmount, onMounted, reactive} from 'vue'
    function savePoint(){
      // 实现鼠标“打点”的数据
      let point = reactive({
        x: 0,
        y: 0
      })

      // 实现鼠标“打点”的方法
      function savePoint(e){
        console.log(e.pageX, e.pageY);
        point.x = e.pageX
        point.y = e.pageY
      }

      onMounted(()=>{
        window.addEventListener('click', savePoint)
      })
      onBeforeUnmount(()=>{
        window.removeEventListener('click', savePoint)
      })

      return point
    }

    export default savePoint
    
    在组件中使用
    <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/vuePoint'
        export default {
          name: 'Demo',
          setup() {
            // 数据
            let sum = ref(0)
            let point = usePoint()

            // 返回一个对象(常用)
            return {
              sum,
              point
            }
          },
        }
    </script>

toRef

  • 作用:创建一个 ref 对象,其value值指向另一个对象中的某个属性。
  • 语法:const name = toRef(person,'name')
  • 应用: 要将响应式对象中的某个属性单独提供给外部使用时。
  • 扩展:toRefstoRef功能一致,但可以批量创建多个 ref 对象,语法:toRefs(person)
    setup(){
      //数据
      let person = reactive({
        name:'张三',
        age:18,
        job:{
          j1:{
            salary:20
          }
        }
      })

      // const name1 = person.name
      // console.log('%%%', name1);

      // const name2 = toRef(person, 'name')
      // console.log('###',name2);

      const x = toRefs(person)
      console.log('x',x);

      //返回一个对象(常用)
      return {
        // person,
        // name: toRef(person, 'name'),
        // age: toRef(person, 'age'),
        // salary: toRef(person.job.j1, 'salary')
        ...toRefs(person)
      }
    }