vue3学习之简单hooks使用
hooks是什么?
hooks直译过来是钩,挂钩的意思。前端同学尤其是react的开发者,对这个hooks是比较熟悉的。最近学习vue3发现,官方提供了一些useXxxx的钩子方法,了解下发现是用到了hooks的思想。在阅读了部分vue3实现的开源项目后,发现项目中使用到hooks确实在一定程度上相当的方便。便有了自己封装简单的hooks的想法。
编写简单的hooks
以编写一个简单的数字步进实现的组件为例,记录在vue3中实现hooks的一些方法。
先看效果:
- ①:正常步进,值为1
- ②:在①的基础上双倍步进
- 两个步进值的和
代码实现
// counterHooks.ts
import { ref, computed } from "vue";
export default function () {
let count = ref(0);
let dbCount = computed(() => {
return count.value * 2;
});
let increment = () => count.value++;
let decrement = () => count.value--;
return {
count,
dbCount,
increment,
decrement,
};
}
页面引用
<template>
<div>
<h1>\(^o^)/~ hooks简单示例</h1>
<h1>①:当前值:{{ count }}</h1>
<h1>②:当前值*2:{{ dbCount }}</h1>
<button @click="increment">+1</button> |
<button @click="decrement">-1</button>
<br />
<h1>①+② = {{ count + dbCount }}</h1>
</div>
</template>
<script setup lang="ts">
import userCount from "../hook-js/counterHooks.ts";
let { count, dbCount, increment, decrement } = userCount();
</script>
<style>
</style>
实现思想
通过ts(js)代码的方式,将业务逻辑代码通过函数的方式暴露出来,使用的位置导入后调用对应的函数 —— 通过解构操作,将对应暴露出来的属性进行声明并使用。
鉴于此,由于暴露出来的属性并不限制其类型,所以可以将业务逻辑中的方法暴露出来,进一步就可以通过函数传参的操作,完成一些较为复杂的逻辑操作:
import { ref, computed } from "vue";
export default function () {
let count = ref(0);
let dbCount = computed(() => {
return count.value * 2;
});
let increment = () => count.value++;
let decrement = (limit: boolean) => {
if (limit && count.value >= 1) {
return count.value--;
} else {
return alert("最小值不能小于0");
}
};
return {
count,
dbCount,
increment,
decrement,
};
}
调用时
<script setup lang="ts">
import userCount from "../hook-js/counterHooks.ts";
let { count, dbCount, increment, decrement } = userCount();
decrement(false);
</script>
其他
关于hooks,理解的还很浅薄,vue3的知识也在学习中。希望提供宝贵的经验及建议。