比較簡單的小demo,直接上代碼吧vue
ts使用defineComponent,setup()裏面使用 Composition API 寫法,邏輯塊清晰,不用先後文查找,拒絕 spaghetti code
react
<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傳複雜變量(對象),效果就是這樣this
再貼一下模板代碼吧spa
<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好不少。code