1、安装
npm i @vueuse/core
2、新建index.ts文件引入想要使用的方法
/*
* @description: 自定义 ts
* @Author: yp
* @Date: 2024-01-27
* @LastEditors: yp
* @LastEditTime: 2024-01-27
*/
// 【自定义hook】
// 什么是hook?—— 本质是一个函数,把setup函数中使用的Composition API进行了封装,类似于vue2.x中的mixin。
// 自定义hook的优势:复用代码, 让setup中的逻辑更清楚易懂。
import { reactive, onMounted, getCurrentInstance } from 'vue'
import { useLocalStorage, useMouse, usePreferredDark } from '@vueuse/core'
export default function () {
const { x, y } = useMouse()
// is user prefers dark theme
const isDark = usePreferredDark()
// persist state in localStorage
const LocalStore = useLocalStorage(
'my-storage',
{
name: 'Apple',
color: 'red',
},
)
// //向外部暴露数据
return {x, y, isDark, LocalStore }
}
3、在组件中引入
<template>
<div>
<div>{{ x }} {{ y }}</div>
</div>
</template>
<script lang="ts">
// import { logicalExpression } from "@babel/types";
// 在setup语法中,组件导入之后就能够直接使用,不需要使用components进行局部注册
// ref定义数据:操作数据需要 .value ,读取数据时模板中直接读取不需要 .value
// reactive 定义的数据: 操作数据和读取数据均不需要 .value
import {
defineComponent,
reactive,
toRefs,
ref,
getCurrentInstance,
computed,
watch,
onMounted,
onUpdated,
onUnmounted,
} from "vue";
import useLoginHook from "../hook/login";
export default defineComponent({
name: "login",
props: {},
setup: (props, context) => {
// props:值为对象,包含: 组件外部传递过来,且组件内部声明接收了属性
// context:上下文对象
// attrs: 值为对象,包含:组件外部传递过来,但没有在props配置中声明的属性,相当于 this.$attrs
// slots:收到插槽的内容,相当于$slots
// emit: 分发自定义事件的函数,相当于this.$emit
const { x, y, isDark, LocalStore } = useLoginHook();
let xPoint = ref(x);
let yPoint = ref(y);
return {
x,
y,
};
},
});
</script>
<style lang="less"></style>