自定义hook函数

发布时间 2023-07-10 22:42:18作者: TestRookie
  • 什么是hook?—— 本质是一个函数,把setup函数中使用的Composition API进行了封装。

  • 类似于vue2.x中的mixin。

  • 自定义hook的优势: 复用代码, 让setup中的逻辑更清楚易懂。

 

创建hook3文件夹

新建usePoint.js文件(文件名以userxxx命名)

 

app.vue

<template>
  <button @click="isShow = !isShow">展示/隐藏</button>
  <Demo4 v-if="isShow"></Demo4>
</template>

<script>

import Demo4 from './components/Demo4'
import {ref} from 'vue'

export default {
  name: 'App',
  components:{
    Demo4
  },
  setup() {
    let isShow = ref(true)

    return {isShow}
  }
 
}
</script>

<style>

</style>

  

Deme4.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() {
    let sum = ref(0)
    
    let point = usePoint()

    //返回一个对象
    return{sum,point}

  }
 
}
</script>

<style>

</style>