VUE3-自定义hook(12)

本案例需要关闭语法检查。
hook的使用就是模块化的思想,我们可以将一些公共的方法封装为一个js文件,放入hooks文件夹,这样所有组件都可以调用这个js文件,从而使得组件内部简单明了。

目录结构

App.vue

<template>
  <button @click="isShowDemo = !isShowDemo">切换隐藏/显示</button>
  <Demo v-if="isShowDemo"/>
  <hr>
  <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() {
     
     
    let isShowDemo = ref(true)
    return {
     
     isShowDemo}
  }
}
</script>

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
}

components文件夹下的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() {
     
     
    let sum = ref(0)
    let point = usePoint()

    return {
     
     sum, point}
  }
}
</script>

components文件夹下的Test.vue

<template>
  <h2>我是Test组件</h2>
  <h2>当前点击时鼠标的坐标为[x:{
   
   { point.x }}, y:{
   
   { point.y }}]</h2>
</template>

<script>
import usePoint from '../hooks/usePoint'

export default {
     
     
  name: 'Test',
  setup() {
     
     
    const point = usePoint()
    return {
     
     point}
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/gty204625782/article/details/123403569