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