目录 正文 todoList demo 目录结构 TodoList.vue代码如下 定义的类型文件 逻辑抽离 正文 Vue3 中的 Hooks 其实就是业务逻辑的抽离,跟 Vue2 中 mixin 本质上是一样的:将当前组件的业务逻辑抽离到
目录
- 正文
- todoList demo
- 目录结构
- TodoList.vue代码如下
- 定义的类型文件
- 逻辑抽离
正文
Vue3中的Hooks 其实就是业务逻辑的抽离,跟Vue2中mixin 本质上是一样的:将当前组件的业务逻辑抽离到一个公共的文件中,提高逻辑复用性,让当前组件看起来更加清爽,不太一样的地方是我们封装hooks 的时候一般是返回一个函数。
todoList demo
先来看一个简单的例子:todoList demo。
新建一个Vue3+Ts的项目: npm init vite@latest 项目名称:vue3-hooks, 使用TS,然后cd vue3-hooks -> npm install -> npm run dev 然后删除不必要的内容,新建一个type 文件夹存放所有的类型,新建一个TodoList.vue编写我们的业务和视图代码:
目录结构

TodoList.vue代码如下
<template>
<h1>To do List</h1>
添加一条记录: <input type="text" v-model="data.toAddData.title" />
<button @click="onAdd">添加</button>
<br />
<br />
<table>
<thead>
<tr>
<td>id</td>
<td>名称</td>
<td>是否完成</td>
</tr>
</thead>
<tbody>
<tr v-for="item in data.list" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.title }}</td>
<td>{{ item.isFinished }}</td>
</tr>
</tbody>
</table>
</template>
<script setup lang="ts">
import { reactive } from "vue";
import { IntTodoList } from "../type/todoList";
type DataType = {
list: IntTodoList[];
toAddData: IntTodoList;
};
const data = reactive<DataType>({
list: [],
toAddData: {
id: 0,
title: "",
isFinished: false,
},
});
const onAdd = () => {
data.list.push({ ...data.toAddData, id: data.list.length + 1 });
};
</script>
定义的类型文件

interface IntTodoList {
id: number;
title: string;
isFinished: boolean;
}
export type { IntTodoList };
逻辑抽离
- 新建一个
hooks文件夹,在hooks文件夹中新建一个todoList.ts文件,将TodoList.vue中的data数据 和onAdd方法 抽离到hooks文件中,并导出:
import { reactive } from "vue";
import { IntTodoList } from "../../type/todoList";
export default () => {
type DataType = {
list: IntTodoList[];
toAddData: IntTodoList;
};
const data = reactive<DataType>({
list: [],
toAddData: {
id: 0,
title: "",
isFinished: false,
},
});
const onAdd = () => {
data.list.push({ ...data.toAddData, id: data.list.length + 1 });
};
return { data, onAdd}
};
在TodoList.vue 中导入:
<template>
<h1>To do List</h1>
添加一条记录: <input type="text" v-model="data.toAddData.title" />
<button @click="onAdd">添加</button>
<br />
<br />
<table>
<thead>
<tr>
<td>id</td>
<td>名称</td>
<td>是否完成</td>
</tr>
</thead>
<tbody>
<tr v-for="item in data.list" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.title }}</td>
<td>{{ item.isFinished }}</td>
</tr>
</tbody>
</table>
</template>
<script setup lang="ts">
import TodoListHooks from './hooks/todoList'
const {data, onAdd} = TodoListHooks()
</script>
如果其他组件需要data 数据 和 onAdd 方法,也可以导入hooks 文件使用,而且现在再来看TodoList.vue 文件看上去是不是非常清爽。 功能跟未抽离前是一样的:

完整代码
以上就是Vue3 Hooks 模块化抽离示例详解的详细内容,更多关于Vue3 Hooks 模块化抽离的资料请关注易盾网络其它相关文章!
