Original source: https://michaelnthiessen.com/inline-composables
Last active
June 5, 2024 18:03
-
-
Save Kcko/f5e43bd7c07320fd7e16b80aaa7dd0a8 to your computer and use it in GitHub Desktop.
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
<template> | |
<div v-for="counter in listOfCounters" :key="counter.id"> | |
<button @click="counter.decrement()">-</button> | |
{{ counter.count }} | |
<button @click="counter.increment()">+</button> | |
</div> | |
</template> | |
<script setup> | |
import { ref, reactive } from 'vue' | |
const listOfCounters = []; | |
for (let i = 0; i < 10; i++) { | |
const counter = reactive({ | |
id: i, | |
count: 0, | |
increment() { | |
this.count += 1; | |
}, | |
decrement() { | |
this.count -= 1; | |
}, | |
}) | |
listOfCounters.push(counter); | |
} | |
</script> | |
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
// muze byt samozrejme pouzito i s reactive, | |
// je to jen demonstrace tovarny kde se pouziva this, | |
// namisto 03 - composable jak se bezne pouziva | |
<script setup> | |
import { ref, reactive } from 'vue' | |
const createCounter = (i) => ({ | |
/* this = | |
{id: 4, count: RefImpl, increment: ƒ, decrement: ƒ} | |
*/ | |
id: i, | |
count: ref(0), | |
increment() { | |
this.count.value += 1; | |
}, | |
decrement() { | |
this.count.value -= 1; | |
}, | |
}); | |
const listOfCounters = []; | |
for (let i = 0; i < 10; i++) { | |
listOfCounters.push(createCounter(i)); | |
} | |
</script> |
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
const useCount = (i) => { | |
const count = ref(0); | |
const increment = () => count.value += 1; | |
const decrement = () => count.value -= 1; | |
return { | |
id: i, | |
count, | |
increment, | |
decrement, | |
}; | |
}; | |
const listOfCounters = []; | |
for (const i = 0; i < 10; i++) { | |
listOfCounters.push(useCount(i)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment