09. Vue3中模块化介绍-实现一个时间更新模块

目录
文章目录隐藏
  1. 让程序变的人性化
  2. 先实现功能
  3. 独立模块化的使用
  4. 引入并使用模块

Vue3.x 版本最大的一个提升,就是有更好的重用机制,你可以把任何你想独立的模块独立出去。比如在 P08 节的基础上,加一个显示当前时间的功能(例如:15:07:20)。并且这个功能要在不同的页面进行反复调用。

使用 Vue2.x 的版本,一定会使用mixins进行代码的重用。当有Vue3.x

让程序变的人性化

为了方便学习,我们把程序中大部分代码删除掉,修改为下面的样子。

<template>
  <div>
  </div>
</template>
<script lang="ts">
import { ref } from "vue";
const app = {
  name: "App",
  setup() {

  },
};
export default app;
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

然后就可以编写代码了

先实现功能

先来看不重用的写法,也就是我们把程序直接写在App.vue这个组件里。这里你可以先顶一个ref变量nowTime,然后通过getNowTime的方法,让他可以显示并一直更新当前时间。最后在return里返回这个变量和方法。

//....
const app = {
  name: "App",
  setup() {
    //.....
    const nowTime = ref("00:00:00");
    const getNowTime = () => {
      const now = new Date();
      const hour = now.getHours() < 10 ? "0" + now.getHours() : now.getHours();
      const minu =now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
      const sec =now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds();
      nowTime.value = hour + ":" + minu + ":" + sec;
      setTimeout(getNowTime, 1000);   //每一秒执行一次这个方法
    };
    //...
    return {
      //....
      nowTime,
      getNowTime,
    };
  },
};
export default app;

然后你需要在template里使用他们,代码如下:

<div>{{ nowTime }}</div>
<div><button @click="getNowTime">显示时间</button></div>

这样就可以在浏览器里看到初始时间00:00:00,点击按钮后,开始显示当前时间,并一直更新。

独立模块化的使用

这个显示时间的方法,可能在其他页面中也会使用,所以现在的需求是把这个时间显示的功能进行模块和重用化。

可以在src目录下,新建一个文件夹hooks(所有抽离出来的功能模块都可以放到这个文件夹里),然后再新建一个文件useNowTime.ts,这里使用use开头是一个使用习惯,代表是一个抽离出来的模块。

有了模块之后,我们就可以把写的代码复制到useNowTime.ts文件里了。然后进行必要的修改。

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 minu =
        now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
    const sec =
        now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds();
    nowTime.value = hour + ":" + minu + ":" + sec;

    setTimeout(getNowTime, 1000);
};

export { nowTime, getNowTime }

需要注意的是,你需要在代码的最前面用 import 进行引入 ref,在最后用 export 的方式,导出 nowTime 和 getNowTime。

引入并使用模块

模块写好了,回到App.vue页面,现在可以引入并使用模块了。

引入代码:

import { nowTime, getNowTime } from "./hooks/useNowTime";

然后记得,要用 return 进行导出哦

return {nowTime,getNowTime};

现在可以看出这种方式,比 vue2 中要好很多,不用再使用mixins(混入)要好很多。我觉的这个算是 Vue3.x 一个非常重要的改进。

为了方便大家学习,我这里把完整代码附上

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <h2>欢迎光北海九号主题餐厅</h2>
  <div>请选择一位美女服务员</div>
  <div>
    <button 
      v-for="(item,index) in girls"
      v-bind:key="index"
      @click="selectGirlFun(index)"
      >
      {{index}}:{{item}}
    </button>
  </div>
  <div>你选择【{{ selectGirl }}】服务员为你服务</div>
  <div><button @click="overAction">点餐完毕</button></div>
  <div>{{ overText }}</div>
  <div>{{ nowTime }}</div>
  <div><button @click="getNowTime">显示时间</button></div>
</template>

<script lang="ts">

// reactive()
import {
  ref,
  reactive,
  toRefs,
  watch
  } from 'vue';
import { nowTime, getNowTime } from "../src/hooks/useNowTime";

interface DataProps {
  girls: string[];
  selectGirl: string;
  selectGirlFun: (index: number) => void;
}

export default ({
  name: 'App',
  setup(){
    console.log("1.开始创建组件 -----setup()")
    const data: DataProps = reactive({
      girls: ["小红","小李","小张",],
      selectGirl: "",
      selectGirlFun: (index: number) => {
        data.selectGirl = data.girls[index];
      }
    });

    const refData = toRefs(data);

    const overText = ref("北海九号");
    const overAction = () => {
      overText.value = "点餐完成 | " + overText.value;
    }

    watch([overText,()=>data.selectGirl],(newValue,oldValue)=>{
      console.log(`newValue ----- + ${newValue}`);
      console.log(`oldValue ----- + ${oldValue}`);
      document.title = newValue[0];
    })
    return {
      ...refData,
      overText,
      overAction,
      nowTime,
      getNowTime
    };
  }
});
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » 09. Vue3中模块化介绍-实现一个时间更新模块

发表回复