咱们晓得当程序有肯定的可重用性时,在vue2中咱们会应用mixins,然而在vue3中没有了。那咱们先vue3中怎么实现相似的性能了。
明确需要,咱们心愿有提供一个工夫与调用工夫的办法给多个组件应用。咱们先新建一个Time.vue组件
<template> <div class="time"> <button @click="getNowTime">获取工夫</button> <div>{{ nowTime }}</div> </div></template><script lang="ts">import { defineComponent, reactive, ref, toRefs, watch } from "vue";export default defineComponent({ name: "about", setup() { const nowTime = ref("00:00:00"); const getNowTime = () => { const now = new Date(); const hour = now.getHours() < 10 ? "0" + now.getHours() : now.getHours(); const min = now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes(); const sec = now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds(); nowTime.value = hour + ":" + min + ":" + sec; setTimeout(getNowTime, 1000); }; return { nowTime, getNowTime, }; }, components: {},});</script><style lang="scss" scoped>.about { margin-top: 80px;}</style>
当咱们点击“获取工夫”按钮后
获取了以后工夫,并1秒钟刷新一次,曾经能够失常运行了。那咱们想在多个组件中应用这个工夫跟办法该如果实现了。
- 模块化
新建一个hooks文件夹并新建一个time.ts文件
把相干代码写在time.ts中,并export
进来
import { ref } from "vue";const nowTime = ref("00:00:00");const getNowTime = () => { const now = new Date(); const hour = now.getHours() < 10 ? "0" + now.getHours() : now.getHours(); const min = now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes(); const sec = now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds(); nowTime.value = hour + ":" + min + ":" + sec; setTimeout(getNowTime, 1000);};export { nowTime, getNowTime }
在须要应用的组件中援用
<template> <div class="time"> <button @click="getNowTime">获取工夫</button> <div>{{ nowTime }}</div> </div></template><script lang="ts">import { defineComponent } from "vue";import { nowTime, getNowTime } from "@/hooks/time";export default defineComponent({ name: "about", setup() { return { // 这里还须要return,切记不能遗记 nowTime, getNowTime, }; }, components: {},});</script><style lang="scss" scoped>.about { margin-top: 80px;}</style>
程序仍然失常运行