/ Gists / Vue.js: Inline composables
On gists

Vue.js: Inline composables

Popular ⭐ Vue.js

readme.md Raw #

01-with-reactive.js Raw #

<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>

02-with-ref-factory.js Raw #

// 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>

03-inline-composable.js Raw #

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 (let i = 0; i < 10; i++) {
  listOfCounters.push(useCount(i));
}


// nebo verze s "this"

const useCount = (i) => {

   return {
    id: i,
    count: ref(0),
    increment() {
      this.count.value += 1;
    },
    decrement() {
      this.count.value -= 1;
    },
  };
};