我们知道当程序有一定的可重用性时,在vue2中我们会使用mixins,但是在vue3中没有了。那我们先vue3中怎么实现类似的功能了。

  1. 明确需求,我们希望有提供一个时间与调用时间的方法给多个组件使用。我们先新建一个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>


alt

当我们点击“获取时间”按钮后

alt

获取了当前时间,并1秒钟刷新一次,已经可以正常运行了。那我们想在多个组件中使用这个时间跟方法该如果实现了。

  1. 模块化
    新建一个hooks文件夹并新建一个time.ts文件
    alt
    把相关代码写在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>

程序依然正常运行
alt