其他分享
首页 > 其他分享> > hook

hook

作者:互联网

什么是hook?

<template>
  <div>{{sum}}</div>
  <button @click="sum++">自增</button>
  <div>坐标 {{point.x}} ---- {{point.y}}</div>
</template>

<script>
import {ref, reactive, onMounted, onBeforeUnmount, } from 'vue'
export default {
  name: 'Demo',
  setup() {
    let sum = ref(1)
    let point = reactive({
      x: 0,
      y: 0
    })
    // 用于保存坐标信息
    function savePoint(event) {
      console.log(event.pageX, event.pageY);
      point.x = event.pageX
      point.y = event.pageY
    }
    onMounted(() => { // 组件挂载完毕后立即执行该生命周期钩子函数
      window.addEventListener('click', savePoint)
    })
    onBeforeUnmount(() => { // 组件即将被卸载时 执行该生命周期钩子函数
      window.removeEventListener('click', savePoint)
    })
    return {
      sum,
      point,
    }
  },
}
</script>
<template>
  <div>{{sum}}</div>
  <button @click="sum++">自增</button>
  <div>坐标 {{point.x}} ---- {{point.y}}</div>
</template>

<script>
import {ref, } from 'vue'
import usePoint from "../hooks/usePoint";
export default {
  name: 'Demo',
  setup() {
    let sum = ref(1)
    let point = usePoint() // usePoint是封装的一个 hook
    return {
      sum,
      point,
    }
  },
}
</script>
import {onBeforeUnmount, onMounted, reactive} from "vue";

export default function() {
  // 坐标数据
  let point = reactive({
    x: 0,
    y: 0
  })
  // 用于保存坐标信息的函数
  function savePoint(event) {
    console.log(event.pageX, event.pageY);
    point.x = event.pageX
    point.y = event.pageY
  }
  onMounted(() => { // 组件挂载完毕后立即执行该生命周期钩子函数
    window.addEventListener('click', savePoint)
  })
  onBeforeUnmount(() => { // 组件即将被卸载时 执行该生命周期钩子函数
    window.removeEventListener('click', savePoint)
  })

  // 暴露数据给外部使用
  return point
}

标签:savePoint,point,sum,hook,let,event
来源: https://www.cnblogs.com/xiebenyin-/p/15856540.html