一、Hooks/CountHook.js

  1. import { reactive, toRefs } from "vue"
  2. export const useCounter = ()=>{
  3. const state = reactive({
  4. count:0,
  5. add(){
  6. state.count++
  7. }
  8. })
  9. const refState = toRefs(state);
  10. return refState
  11. }

二、父组件

  1. <template>
  2. <div>
  3. <button @click="add">{{count}}</button>
  4. </div>
  5. </template>
  6. <script setup>
  7. import {useCounter} from './Hooks/CountHook'
  8. const {add,count}=useCounter()
  9. </script>