亲宝软件园·资讯

展开

Vue3 hooks函数

​ tangdou369098655   ​ 人气:0

前言

项目开发过程中,我们会遇到一些情况,就是多个组件都可以重复使用的一部分代码逻辑,功能函数,我们想要复用,这可怎么办呢?

VUE2我们是怎么做的呢?

VUE3中我们怎么处理复用代码逻辑的封装呢?

说那么多,不如直接上代码来看差异

先来一段我们的一把梭代码,代码没有复用,全都放到当前组件

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <div>
    VUE3中的HOOKS
  </div>
  <button @click="setNumber">点击此按钮,调用setNumber函数,数字会+1:{{myNumber}}</button>
  <button @click="a++">点击此按钮,数字会+1:{{a}}</button>
  <button @click="b--">点击此按钮,数字会-1:{{b}}</button>
</template>
<script>
import { reactive,ref,computed,watch,watchEffect } from "vue";
export default {
  setup(){
    const  myNumber = ref(0)
    const  a = ref(0)
    const  b = ref(0)
    const setNumber = ()=>{
      myNumber.value = myNumber.value+1;
    }
    watch([a,b],([newA,newB],[oldA,oldB])=>{
      console.log('newA,oldA:')
      console.log(newA,oldA)
      console.log('newA,oldB:')
      console.log(newA,oldB)
    })
    return{
      myNumber,
      a,
      b,
      setNumber
    }
  }
}
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
  
}
button{
    display: block;
    margin: 0 auto;
  }
</style>

执行代码看一下:

import { ref,watch } from "vue";
export const useNumber =() =>{
    const  myNumber = ref(0)
    const  a = ref(0)
    const  b = ref(0)
    const setNumber = ()=>{
      myNumber.value = myNumber.value+1;
    }
    watch([a,b],([newA,newB],[oldA,oldB])=>{
      console.log('newA,oldA:')
      console.log(newA,oldA)
      console.log('newA,oldB:')
      console.log(newA,oldB)
    })
    return{
      myNumber,
      a,
      b,
      setNumber
    }
}

改写一下我们的模板代码里的script:

<script>
import { useNumber } from "./common-hooks/numberChange";
export default {
  setup() {
    const { myNumber, a, b, setNumber } = useNumber();
    return { myNumber, a, b, setNumber };
  },
};
</script>

加载全部内容

相关教程
猜你喜欢
用户评论