Vue3
中的Hooks
其实便是事务逻辑的抽离,跟Vue2
中mixin
本质上是相同的:将当时组件的事务逻辑抽离到一个公共的文件中,进步逻辑复用性,让当时组件看起来更加清爽,不太相同的地方是咱们封装hooks 的时候一般是返回一个函数。
先来看一个简略的比如: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
文件看上去是不是非常清爽。
功能跟未抽离前是相同的:
完整代码