Vue3?Hooks?模塊化抽離示例詳解
正文
Vue3
中的Hooks
其實就是業(yè)務邏輯的抽離,跟Vue2
中mixin
本質(zhì)上是一樣的:將當前組件的業(yè)務邏輯抽離到一個公共的文件中,提高邏輯復用性,讓當前組件看起來更加清爽,不太一樣的地方是我們封裝hooks 的時候一般是返回一個函數(shù)。
todoList demo
先來看一個簡單的例子:todoList
demo。
新建一個Vue3+Ts的項目: npm init vite@latest
項目名稱:vue3-hooks
, 使用TS
,然后cd vue3-hooks
-> npm install
-> npm run dev
然后刪除不必要的內(nèi)容,新建一個type
文件夾存放所有的類型,新建一個TodoList.vue
編寫我們的業(yè)務和視圖代碼:
目錄結構
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
數(shù)據(jù) 和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
數(shù)據(jù) 和 onAdd
方法,也可以導入hooks
文件使用,而且現(xiàn)在再來看TodoList.vue
文件看上去是不是非常清爽。 功能跟未抽離前是一樣的:
以上就是Vue3 Hooks 模塊化抽離示例詳解的詳細內(nèi)容,更多關于Vue3 Hooks 模塊化抽離的資料請關注腳本之家其它相關文章!
相關文章
vue.js項目 el-input 組件 監(jiān)聽回車鍵實現(xiàn)搜索功能示例
今天小編就為大家分享一篇vue.js項目 el-input 組件 監(jiān)聽回車鍵實現(xiàn)搜索功能示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08Vue $emit $refs子父組件間方法的調(diào)用實例
今天小編就為大家分享一篇Vue $emit $refs子父組件間方法的調(diào)用實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09