vue3中自定义hooks(封装模块)

115 阅读1分钟

默认写组件vue的方式如下

<script setup lang="ts">
import { ref } from 'vue'

const dataOne = ref('数据One')

const dataTwo = ref('数据Two')

const methodOne = () => {
  console.log('这是一', dataOne.value)
}
const methodTwo = () => {
  console.log('这是二', dataTwo.value)
}
</script>

<template>
  <h1>{{ dataOne }}--{{ dataTwo }}</h1>
  <button @click="methodOne">封装hooks一</button>
  <button @click="methodTwo">封装hooks二</button>
</template>

如上代码就是数据ref和方法没有分类,应该将方法一和数据一整合在一起,方法二和数据二整合在一起

自定义hooks进行组合,如下,先在src目录下创建hooks文件夹,再创建以use开头+封装的功能名的ts或js文件

image.png

useDataOne.ts

import { ref } from 'vue'

export default function () {
  const dataOne = ref('数据One')
  const methodOne = () => {
    console.log('这是一', dataOne.value)
  }
  return { dataOne, methodOne }
}

useDataTwo.ts

import { ref } from 'vue'
export default function () {
  const dataTwo = ref('数据Two')
  const methodTwo = () => {
    console.log('这是二', dataTwo.value)
  }
  return { dataTwo, methodTwo }
}

组件中的使用

<script setup lang="ts">
import useDataOne from '@/hooks/useDataOne'
import useDataTwo from '@/hooks/useDataTwo'

let { dataOne, methodOne } = useDataOne()
let { dataTwo, methodTwo } = useDataTwo()
</script>

<template>
  <h1>{{ dataOne }}--{{ dataTwo }}</h1>
  <button @click="methodOne">封装hooks一</button>
  <button @click="methodTwo">封装hooks二</button>
</template>