vue3的hooks用法

news/2025/3/15 16:37:59/

vue2使用习惯了以后,mixins这种复用性极高的功能肯定是避免不了常用的,当使用vue3的时候,也想要类似于mixins这种功能,应该咋弄呢。
1.vue2的mixins中有data,watch,methods, mounted等,对应vue3中hooks的写法是咋样呢。
先拿出一个完整的hooks来看吧,写法是自己参考网上百度到的进行改进,也可根据自己的需要再改。
myHooks.tsx

import { Select, SelectOption } from 'ant-design-vue'
export default function (props: any) {const countValue= ref(1)const selectList = ['张三', '李四', '王五']let columns = [{title: '姓名',dataIndex: 'name',align: 'center',customRender: ({ record }: { record: any }) => {return (<div><Select v-model:value={record.name} placeholder="" onChange={(e:any)=>nameChange(e)}>{selectList.map((item: any,dex:any) => {return <SelectOption key={dex} value={item}> { item } </SelectOption>})}</Select></div>)}},{title: '年龄',dataIndex: 'age',align: 'center'},{title: '身高',dataIndex: 'height',align: 'center'}]onMounted(() => {console.log('onMounted')})watch(() => props.group,val => {nameChange(0)})function nameChange(val: any) {console.log(val)countValue.value += 1 }return { columns, nameChange}
}

上面的ref对应vue2中mixins的data变量,onMounted对应vue2的mixins生命周期,watch也是一样,函数直接写在最外层即可。
2.在页面中引用这个myHooks.tsx时,就是下面这样

<template><a-table bordered :columns="columns" :pagination="false" :data-source="list"> </a-table>
</template>
<script setup lang="tsx">
import myHooks from '/myHooks'
const props = defineProps({list: {type: Array,default: () => [],required: true},group: {type: String,default: () => ''}
})
let columns = ref([{title: '分组',dataIndex: 'group',align: 'center'},{title: '业务',dataIndex: 'bussiness',align: 'center'},{title: '费用',dataIndex: 'total',align: 'center'}
])
let obj: any = myHooks(props)
columns.value.push(...obj.columns)
</script>

在组件的最外层调用myHooks会执行里面的生命周期,watch等。通用性也很高,可以将复用的逻辑全部封装到里面。像table组件的分页逻辑,删除第二页只有一条数据时,切换到第一页等功能完全可以用hooks这种方式实现。不用再每次写页面一次次写里面的逻辑,直接调hooks,把方法导入就行。
3.and-design-vue中table用法,封装分页和请求功能。
myPage.tsx

import {  Table, Button } from 'ant-design-vue'
import useTable from 'useTable'export default defineComponent({setup(props, { emit }) {const columns: any = [{ title: '姓名', dataIndex: 'name', align: 'center' },{ title: '年龄', dataIndex: 'age', align: 'center' },{ title: '性别', dataIndex: 'sex', align: 'center' }]const serves = (obj: any) => {return axios.get(`https://baidu.com`, { params: obj })}const { data, run, loading, params, tableChange, paginationConfig } = useTable(serves)function search(e: any) {let vo = {current: 1,size: 10,keyword: e.keyword || '',}run(vo)}return () => {return (<div><Button onClick={()=>{search}}>搜索</Button><Tablescroll={{ x: 600 }}columns={columns}loading={loading.value}bordereddata-source={data.value?.records || []}onChange={tableChange}pagination={paginationConfig}/></div>)}}
})

useTable.ts

import { useRequest } from 'vue-request'
import { Options } from 'vue-request/dist/types/index'
import { ref } from 'vue'const useTable = (service: any, pageConfig?: any, option?: Options<any, any>) => {const current = ref(1)const pageSize = ref(10)const paginationConfig: any = ref({total: 0,showTotal: (e: any) => `${e}条记录`,showSizeChanger: true,showQuickJumper: true,current: 1,pageSize: 10})let curentKey = pageConfig?.current || 'current'let pageSizeKey = pageConfig?.pageSize || 'pageSize'const { data, run, refresh, loading, params, error } = useRequest(async p => {const res = await service(p)return res.data},{manual: true,onSuccess: () => {current.value = params.value[0][curentKey]pageSize.value = params.value[0][pageSizeKey]Object.assign(paginationConfig.value, { total: data.value?.total || 0, current: current.value, pageSize: pageSize.value })},...option})function tableChange(v: any) {run({...params.value[0],[curentKey]: v.current,[pageSizeKey]: v.pageSize})}function refreshList(type?: 'del') {if (type === 'del' && data.value?.data.size === 1) {run({...params.value[0],[curentKey]: params.value[0].current - 1})} else {refresh()}}return {data,loading,error,params,run,paginationConfig,refresh: refreshList,tableChange}
}
export default useTable

http://www.ppmy.cn/news/1209161.html

相关文章

Android---App 崩溃

崩溃问题是衡量 App 质量的决定性考核标准。Android 系统会输出各种相应的 log 日志&#xff0c;很大程度上降低了工程师 debug 崩溃问题的难度。如果要给 crash 日志进行分类&#xff0c;可以分为2大类&#xff1a;JVM 异常&#xff08;Exception&#xff09;堆栈信息和 nativ…

leetcode_2233. K 次增加后的最大乘积

题目链接&#xff1a;2233. K 次增加后的最大乘积 - 力扣&#xff08;LeetCode&#xff09; // 小根堆#define INVALUE ((int)pow(10, 6) 1) #define MOD ((int)pow(10, 9) 7)static int cmp(const void *a, const void *b) {return (*(int*)a - *(int*)b); }int maximu…

计算机网络第一章(计算机网络开篇)

目录 一.什么是计算机网络1.0 何为计算机网络1.1 什么是Internet?1.2 互联网与互连网1.3 互联网基础结构发展的三个阶段 二.什么是网络协议2.1 协议的三要素2.2 internet协议标准 三. 互联网的组成3.1 边缘部分3.11 端系统之间的通信 3.2 核心部分3.21 数据交换技术 四. 计算机…

Android帧率修改

1.app设置帧率 影响范围&#xff1a;仅影响当前App&#xff0c;退出App后帧率恢复正常参考代码 // 读取系统支持的Display mode Display defaultDisplay getWindowManager().getDefaultDisplay(); Display.Mode[] supportedModes supportedModes defaultDisplay.getSupport…

界面组件DevExpress ASP.NET Core v23.1 - 进一步升级UI组件

DevExpress ASP.NET Core Controls使用强大的混合方法&#xff0c;结合现代企业Web开发工具所期望的所有功能。该套件通过ASP.NET Razor标记和服务器端ASP.NET Core Web API的生产力和简便性&#xff0c;提供客户端JavaScript的性能和灵活性。ThemeBuilder工具和集成的Material…

统信UOS Linux操作系统下怎么删除某个程序在开始菜单或桌面的快捷方式

☞ ░ 前往老猿Python博客 ░ https://blog.csdn.net/LaoYuanPython 引言 统信操作系统的开始菜单包罗万象&#xff0c;将所有应用的快捷方式都放在了开始菜单内。 虽然提供了分类展示的能力&#xff0c;但无论是分类方式还是未分类方式&#xff0c;都不能像windows一样将这…

基于springboot实现高校党务平台管理系统【项目源码】

基于springboot实现高校党务平台管理系统演示 Java技术 Java是由Sun公司推出的一门跨平台的面向对象的程序设计语言。因为Java 技术具有卓越的通用性、高效性、健壮的安全性和平台移植性的特点&#xff0c;而且Java是开源的&#xff0c;拥有全世界最大的开发者专业社群&#x…

git-bash配置代理

git-bash命令提交执行命令: "git push origin main"时发生错误: “$ git push origin main fatal: unable to access ‘https://github.com/satadriver/locust_server.git/’: Failed to connect to github.com port 443 after 21035 ms: Couldn’t connect to serve…