V3-浩克死(hooks)基本用法

75 阅读1分钟
// 回顾 vue2 ximins
// mixins 对象的方式混入钩子函数
export const mixinLyon = {
  data() {
    return {
      'Lyon': '真男人'
    }
  },
  created(){},
  mounted() {},
  computed: {},
  methods: {},
}

// 组件中使用
import { mixinLyon } 'xxx/xxx.js'
export default {
  mixins: [mixinLyon] // 引入
}
浩克死(hooks:钩子) 可以理解为 mixin的变体,处理公共的业务逻辑,抽离成一个单独的ts 方法体,方便逻辑复用
###  Hook 部分
// src/hooks/hookLyon.ts
// demo模拟一个存钱 贷款的方法逻辑
import {computed, ref, Ref} from 'vue'

// ts 定义类型 真很烦人 啰里八嗦还要处理各种 声明报错问题
type Bank = {
  enterManei:Ref<number>;
  saveManei:(money:number,year:number)=>void;
  loanManei:(money:number,year:number)=>void;
  getManei:Ref<number>;
}

// 导出Hook 方法 | 属性
export default function useLyon (money:number, year=1):Bank {
  console.log('来客了请排队,开一个窗口招待' + money);
  const enterManei = ref(money) // 仅为了定义成响应式数据而已
  const saveManei = (manei:number, year:number): void => {
    console.log('来存钱? 银行按照2%利息给你');
    enterManei.value = (enterManei.value * 0.01 + enterManei.value) * year
  }
  const loanManei =  (manei:number, year:number): void => {
    console.log('来贷款? 你要按照5%利息给银行');
    enterManei.value = (enterManei.value * 0.05 + enterManei.value) * year
  }
  const getManei = computed(() => enterManei.value)
  return {
    enterManei,
    saveManei,
    loanManei,
    getManei
  }
}

hook.ts 引入使用方法 ( pinia 中的 createPinia() 也是个hook )

// template 部分
存钱:<input name="bank" value="save" v-model="typeMoney" type="radio"/>
贷款:<input name="bank" value="loan" v-model="typeMoney" type="radio"/>
<p>银行{{ typeMoney === 'save' ? '存入': '贷款'}}100元 10年:</p>
<button @click="countResult">点击计算</button>:{{ typeMoney === 'save' ? '得到': '欠款' }}:{{ getManei }}
 
 
// scripte setup ts 部分
import hookLyon from '../hooks/hookLyon'
const {  saveManei, loanManei, getManei } = hookLyon()
const typeMoney = ref('save') // 默认 存钱
const countResult = ():void => {
  // 执行某个hook方法(Lyon- Tip: 就是一个方法调用而已,直接作为click 触发也可以)
  if (typeMoney.value === 'save') return saveManei(100, 10)
  return loanManei(100, 10)
}