webfansplz / vuejs-challenges

Collection of Vue.js challenges
https://vuejs-challenges.netlify.app/
MIT License
2.69k stars 188 forks source link

15 - 切换器 #2722

Open Ly-TiR opened 2 months ago

Ly-TiR commented 2 months ago

<script setup lang='ts'>
import {ref} from 'vue'
/**
 * Implement a composable function that toggles the state
 * Make the function work correctly
*/
function useToggle(show:boolean) {
  const state = ref<boolean>(show)

  const toggle = ()=>{
    state.value = !state.value
  }
  return [
    state,
    toggle
  ]
}

const [state, toggle] = useToggle(false)

</script>

<template>
  <p>State: {{ state ? 'ON' : 'OFF' }}</p>
  <p @click="toggle" :style="{color:state ? 'red' : '' }">
    Toggle state
  </p>
</template>