Last active
April 21, 2023 17:21
-
-
Save supermensa/782514759d4179dc7acc2cf3c5929be0 to your computer and use it in GitHub Desktop.
Vue 3 Composition API destructuring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```javascript | |
// src/composables/useCounter.js | |
import { ref } from 'vue'; | |
export default function useCounter() { | |
const count = ref(0); | |
function increment() { | |
count.value++; | |
} | |
function decrement() { | |
count.value--; | |
} | |
function reset() { | |
count.value = 0; | |
} | |
return { | |
count, | |
increment, | |
decrement, | |
reset | |
}; | |
} | |
``` | |
Usage: | |
```html | |
<!-- src/App.vue --> | |
<template> | |
<div id="app"> | |
<h1>Counter App</h1> | |
<p>Current count: {{ count }}</p> | |
<button @click="increment">Increment</button> | |
<button @click="decrement">Decrement</button> | |
<button @click="reset">Reset</button> | |
</div> | |
</template> | |
<script> | |
import useCounter from './composables/useCounter'; | |
export default { | |
setup() { | |
const { count, increment, decrement, reset } = useCounter(); | |
return { count, increment, decrement, reset }; | |
}, | |
}; | |
</script> | |
<style> | |
/* Add your styles here */ | |
</style> | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment