Vue3中自定义hook

hook,本质是一个函数。自定义hook,就是将setup中使用过的组合式函数进行封装,实现代码复用。

看个具体的例子吧。

  • main.js
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')
  • App.vue
<template>
  <button @click="isShowDemo = !isShowDemo">切换(隐藏/显示)button>
  <Demo v-if="isShowDemo"/>
template>

<script>
import Demo from './components/Demo.vue'
import {ref} from "vue";
export default {
  name: 'App',
  components: {
    Demo
  },
  setup(){
    let isShowDemo = ref(true);
    
    return {isShowDemo};
  }
}
script>
  • Demo.vue
<template>
  <h2>sum的当前值为:{{sum}}h2>
  <button @click="sum++">点我+1button>
  <hr>
  <h2>鼠标点击时的坐标,x:{{point.x}},y:{{point.y}}h2>
template>

<script>
import {onBeforeUnmount, onMounted, ref,reactive} from "vue";

export default {
  name: 'Demo',
  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>
  • 启动应用,测试效果
    Vue3中自定义hook_第1张图片
    Demo组件挂载后,鼠标点击页面上任意点,将显示该点的坐标。
    Demo组件被卸载后,将不再监听click事件。

接下来,我们将自定义hook:将pointsavePointonMountedonBeforeUnmount,即把数据、方法、和生命周期钩子封装在一个js文件。
在src目录下新建子目录hooks,并在hooks目录下新建文件: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;
        console.log(event.pageX,event.pageY);
    }

    onMounted(() => {
        window.addEventListener("click",savePoint);
    })

    onBeforeUnmount(() => {
        window.removeEventListener("click",savePoint);
    });

    return point;
}

然后修改Demo.vue,如下所示。

<template>
  <h2>sum的当前值为:{{sum}}h2>
  <button @click="sum++">点我+1button>
  <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(){
    let sum = ref(0);
    let point = usePoint();
    
    return {
      sum,
      point
    }
  }
}
script>

Vue3中自定义hook_第2张图片
Vue3中自定义hook_第3张图片

你可能感兴趣的:(Vue3,hook,组合式API,代码复用)