<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> import { useNumber } from "./common-hooks/numberChange"; export default { setup() { const { myNumber, a, b, setNumber } = useNumber(); return { myNumber, a, b, setNumber }; }, }; </script>
欢迎大家指出文章需要改正之处~
学无止境,合作共赢