vue3自定义Hooks

  比较简单的小demo,直接上代码吧

  ts使用defineComponent,setup()里面使用 Composition API 写法,逻辑块清晰,不用前后文查找,拒绝 spaghetti code 

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue';
// import HelloWorld from '@/components/HelloWorld.vue'; // @ is an alias to /src
import { CountRange, useCount } from '@/composition/use-count';

export default defineComponent({
  name: 'Home',
  // components: {
  //   HelloWorld,
  // },
  props: {
    title2: String
  },
  data() {
    return {
      title1: 'this is title1'
    };
  },
  setup() {
    const title2 = ref('this is title2');

    const range: CountRange = reactive({
      min: 5,
      max: 50
    });

    const { current, minus, plus, set, reset } = useCount(10, range);

    return {
      title2,
      range,
      current,
      minus,
      plus,
      set,
      reset,
    };
  }
});
</script>

 

  useCount

import { ref, Ref, watch } from "vue";

export interface CountRange {
    min: number;
    max: number;
}

interface Result {
    current: Ref<number>;
    minus: (num: number) => void;
    plus: (num: number) => void;
    set: (num: number) => void;
    reset: () => void;
}

export function useCount(init: number, range: CountRange): Result {
    const current = ref(init);

    const minus = (num: number) => {
        current.value -= num;
    };
    const plus = (num: number) => {
        current.value += num;
    };
    const set = (num: number) => {
        current.value = num;
    };
    const reset = () => {
        current.value = init;
    };

    watch(current, (newVal: number, oldVal: number) => {
        if (newVal === oldVal) { return; }
        if (newVal < +range.min) {
            current.value = +range.min;
        } else if (newVal > +range.max) {
            current.value = +range.max;
        }
    });

    return { current, minus, plus, set, reset };
}

 

  比较简单,ref传单一变量,reactive传复杂变量(对象),效果就是这样

 

  

  再贴一下模板代码吧

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png" />
    <!-- <HelloWorld msg="Welcome to Your Vue.js + TypeScript App"/> -->
    <h1>{{ title1 }}</h1>
    <h1>{{ title2 }}</h1>
    <p>current count: {{ current }}</p>
    <div>
      <label>MIN COUNT: </label>
      <input type="number" v-model="range.min" />
    </div>
    <br />
    <div>
      <label>MAX COUNT: </label>
      <input type="number" v-model="range.max" />
    </div>
    <br />
    <button @click="plus(5)">+5</button>
    <button @click="minus(3)">-3</button>
    <button @click="set(233)">set 233</button>
    <button @click="reset()">reset</button>
  </div>
</template>

 

  使用vue和react的hooks之后,明显感觉vue的要简单明了很多,也不会有很多闭包问题、多次调用等,没有太多的限制,很容易上手。这一点做得比react好很多。

posted @ 2020-12-15 10:41  大禹不治水  阅读(14613)  评论(0编辑  收藏  举报