vue单文件组件怎么把逻辑代码抽离为hook

普通的vue单文件组件

log.vue

js 复制代码
<script setup lang="ts">
import { ref } from 'vue';

const index = ref<number>(1)
</script>

<template>
    <h1>{{ index }}</h1>
</template>

<style scoped>
h1 {
    color: red;
    font-size: 50px;
}
</style>

需求

  • 1.把js逻辑代码抽离出去

具体问题链接,前情提要

具体实现

log.hook.ts

js 复制代码
import { ref } from "vue";

export function uselogHook() {
    const index = ref<number>(1);
    
    return {
        index
    }
}

log.vue

js 复制代码
<script setup lang="ts">
import { uselogHook } from "./log.hook";

const { index } = uselogHook()
</script>

<template>
    <h1>{{ index }}</h1>
</template>

<style scoped>
h1 {
    color: red;
    font-size: 50px;
}
</style>

增加需求

  • 1.有一个comoms.ts的文件,其中有一些公共的工具方法暴露出一个类,导入hook在组件中使用

  • 2.props和emits传入hook使用

  • 3.hook中使用生命周期,进行增加监听和移除监听

comoms.ts如下

js 复制代码
export default class Commons {
    constructor() {
    }

    formatTime() {
        console.log('formatTime');
        return new Date().toLocaleString();
    }

}

log.hook.ts

js 复制代码
import { onBeforeUnmount, onMounted, ref } from "vue";
// 导入common.ts
import commonHook from "../common";
export interface Props {
    name: string
}
export interface Emits {
    (e: 'close'): void
}
export function uselogHook(props: Props, emits: Emits) {
    const _props = props
    const _emits = emits
    // 实例化common类
    const common = new commonHook();
    const index = ref<number>(1);
    // 使用传入的参数
    const click = () => {
        console.log(_props.name);
    }

    const keydown = () => {
        console.log("keydown");
        _emits("close");
    }
    onMounted(() => {
        document.addEventListener("keydown", keydown);
    })
    onBeforeUnmount(() => {
        document.removeEventListener("keydown", keydown);
    })

    // 返回变量方法和common实例
    return {
        index, click, keydown, common
    }
}

log.vue

js 复制代码
<script setup lang="ts">
// 导入hook和props,emits类型
import { uselogHook, Props, Emits } from "./log.hook";

// 初始化props,emits
const props = withDefaults(defineProps<Props>(), {
    name: 'default'
})
const emits = defineEmits<Emits>()

// 使用hook传入props,emits  结构出index,click,common
const { index, click, common } = uselogHook(props, emits)
</script>

<template>
    <!-- 显示内容 -->
    <h1 @click="click">{{ index }}</h1>
    <!-- 使用 common公共方法-->
    <h1>{{ common.formatTime() }}</h1>
</template>

<style scoped>
h1 {
    color: red;
    font-size: 50px;
}
</style>
相关推荐
剑亦未配妥26 分钟前
移动端触摸事件与鼠标事件的触发机制详解
前端·javascript
人工智能训练师6 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny076 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy7 小时前
css的基本知识
前端·css
昔人'7 小时前
css `lh`单位
前端·css
前端君8 小时前
实现最大异步并发执行队列
javascript
Nan_Shu_6149 小时前
Web前端面试题(2)
前端
知识分享小能手9 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队10 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光10 小时前
css之一个元素可以同时应用多个动画效果
前端·css