Vue3中如何使用mixin(自定义hook)

669 阅读1分钟

看了一圈基本都是vue2的写法,所以仿照一下

定义mixin

首先在目录src下创建utils/mixin.ts文件,内容如下,遵循vue3组件内script写法,可自行拓展。

import { watch,onMounted, ref } from 'vue'

export const myHook = () => {
  const num = ref(1)
  const numAdd = () => {
    num.value++
    console.log(num.value)
  }
  watch(() => num.value, (newValue, oldValue) => {
    console.log(newValue, oldValue)
  })
  onMounted(() => {
    console.log(num.value)
  })
  return { num, numAdd }
}

如何在组件内使用

src/views/index.vue

注意:这里的引入的方式和router或store一样
<template>
<div @click="numAdd"> {{ num }} </div>
</template>
<script setup lang='ts'>
import { myHook } from 'src/utils/mixin'
const { num, numAdd } = myHook()
</script>

这样就在组件内实现了按需引入