Skip to content

Instantly share code, notes, and snippets.

@Kcko
Last active June 5, 2024 18:03
Show Gist options
  • Save Kcko/f5e43bd7c07320fd7e16b80aaa7dd0a8 to your computer and use it in GitHub Desktop.
Save Kcko/f5e43bd7c07320fd7e16b80aaa7dd0a8 to your computer and use it in GitHub Desktop.
<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>
// 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>
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