春风得意马蹄疾
一日看尽长安花

Vue3.0 Composition API提取公共逻辑

Composition API用于公共逻辑的提取,提高复用性,在Vue2.0中我们可以使用mixins的方式提取一些公共处理逻辑。以记录用户点击屏幕位置为例来说明,显示每次用户鼠标点击屏幕的位置,不考虑代码的复用性,我们会直接写出下面的代码。

<template>
  <p>X: {{x}}, Y: {{y}}</p>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, onUnmounted } from 'vue';
export default defineComponent({
  name: 'App',
  setup(){
    const pointer = reactive({
      x: 0,
      y: 0
    });
    const updateMouse = (e: MouseEvent)=>{
      pointer.x = e.pageX;
      pointer.y = e.pageY;
    };
    onMounted(()=>{
      document.addEventListener("click", updateMouse)
    })
    onUnmounted(()=>{
      document.removeEventListener("click", updateMouse)
    })
    return{
      ...toRefs(pointer)
    }
  }
});
</script>

在VUe3.0中,我们可以考虑把这块获取当前时间的逻辑提取出来,成为一个公共的模块。这个模块与普通Javascript模块类似,只是代码里使用了Vue3.0响应式的变量和Vue3.0内置的方法,通常会将响应式的变量返回出去。实现方法如下:

//新建文件夹 hooks,并新建文件 useMousePosition.ts
import { reactive, onMounted, onUnmounted } from 'vue';
function useMousePosition(){
    const pointer = reactive({
        x: 0,
        y: 0
      });
      const updateMouse = (e: MouseEvent)=>{
        pointer.x = e.pageX;
        pointer.y = e.pageY;
      };
      onMounted(()=>{
        document.addEventListener("click", updateMouse)
      });
      onUnmounted(()=>{
        document.removeEventListener("click", updateMouse)
      });
      return pointer;
}
export default useMousePosition;

那么我们在App.vue中只需要导入useMousePosition,并使用即可

<template>
  <p>X: {{x}}, Y: {{y}}</p>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs} from 'vue';
//导入 useMousePosition
import useMousePosition from './hooks/useMousePosition';
export default defineComponent({
  name: 'App',
  setup(){
    const pointer = useMousePosition();
    return{
      ...toRefs(pointer)
    }
  }
});
</script>
Like
Like Love Haha Wow Sad Angry
赞(1) 打赏
未经允许不得转载:栗子纪blog » Vue3.0 Composition API提取公共逻辑
分享到: 更多 (0)
0 0 vote
Article Rating
Subscribe
提醒
guest
0 评论
Inline Feedbacks
View all comments

创作不易,打赏一下作者买瓶洗发露

支付宝扫一扫打赏

微信扫一扫打赏

0
Would love your thoughts, please comment.x
()
x