4、Vue3中watch的使用和模块化

531 阅读2分钟

一、watch的使用

Vue2中也有watch-监听器(侦听器),作用是用来侦测响应式数据的变化,并且可以得到newValue新值和oldValue老值。

Vue3使用watch同样需要先进行导入.

import {... , watch} from "vue"

引入后编写watch函数,它接受两个参数,第一个是要监听的值,这里是datasName,然后是一个回调函数。在函数中你可以获得到新值和老值。

export default defineComponent({
    name: 'student',
    setup() {
        const data:Data = reactive({
            student:['小明','小红','小王','小李'],
            sName:'',
        })
        const sClick = (index:number):void =>{
            data.sName= data.student[index]
        }
        const refData = toRefs(data)
        watch(refData.sName,(newValue,oldValue) => {
          console.log('新值----'+newValue);
          console.log('旧值----'+oldValue);
        })
       
        return {
            ...refData,
            sClick,
        }
    }
  });

image.png

如果要监听多个值的时候,不是写多个watch函数,而是要传入数组的形式。如下:

watch([refData.sName,() => data.sName],(newValue,oldValue) => {
      console.log('新值----'+newValue);
      console.log('旧值----'+oldValue);
    })

注:数组中refData.sName监听值与() => data.sName为同一个,如果要监听reactive中的值,可以有这两种写法。Vue3不能监听reactive,是为了保持和Vue2的一致性,在Vue2中解决方案是要么是ref或者get/set方法的形式。要么开启设置watchOptions的deep为true,也就是深度监听模式。

二、Vue3模块化

Vue3.x版本最大的一个提升,就是有更好的重用机制,你可以把任何你想独立的模块独立出去。使用Vue2.x的版本,一定会使用mixins进行代码的重用,而Vue3.x版本更加方便,以一个点击显示当前时间功能为例:

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

useNowTime.ts代码如下:

import { ref } from "vue";

const nowTime = ref("");
const getNowTime = () => {
    const now = new Date();
    const Hours = now.getHours() < 10 ? "0" + now.getHours() : now.getHours();
    const Minutes = now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
    const Seconds = now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds();
    nowTime.value = Hours + ":" + Minutes + ":" + Seconds;
    setTimeout(getNowTime, 1000);
};

export { nowTime, getNowTime }

在需要使用获取时间功能界面,引入代码:

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

页面添加显示元素:

 <h2>{{nowTime}}</h2>
 <button @click="getNowTime">获取时间</button>

然后在setup()return进行导出

return {
    ...,
    nowTime,
    getNowTime
 };

image.png

学习日期:2022/1/13

视频参考www.bilibili.com/video/BV1L5…

文档参考jspang.com/detailed?id…

仅供个人学习和记录