DIY: Membuat super simple Vuex clone (centralized global store) sendiri di VueJS

ยท

2 min read

Hi ๐Ÿ™‹๐Ÿปโ€โ™‚๏ธ

Kali ini saya akan membahas cara membuat State Management sendiri di VueJS (Jarang kan saya bahas VueJS ๐Ÿ˜œ)

โ›”๏ธSebelum baca ini, diharapkan sudah memahami basic VueJS

Kalau kita telusuri APInya VueJS, ada API yang sangat berguna namanya Observable API. Di Docs VueJS tidak membahas lebih panjang mengenai API ini tapi kalau diimplementasi ini akan sangat berguna layaknya bikin State Management sendiri

So let's start coding!

Create Store

// store.ts
import Vue from 'vue';

const store = Vue.observable({
   // define your all global initial state here
   data: [], 
   user: {}
})

const mutation = {
   // define your mutation here
   setData: (payload) => {
      store.data = payload
   },
   setUser: (payload) => {
      store.user = Object.assign(store.user, ...payload); 
      // atau bisa pake Vue.set(target, props, value)
   }
}

Usage di Vue Template

<template>
    <div id="app">
        <button @click="fetch">Get the data</button><div v-if="!getData.length">Loading the data</div><div v-else="getData.length">
            <div v-for="data in getData" :key="data.id">
                <h5>{{ data.title }}</h5>
                <p>{{ data.description }}</p>
            </div>
        </div>
    </div>
</template>

<script>
import { store, mutations } from "./store";

export default {
  name: "app",
  computed: {
    getData() {
      return store.data;
    }
  },
  methods: {
    setData: mutations.setData,
    async fetch() {
      const req = await fetch("http://example.com/tasks");
      const res = await req.json();
      return this.setData(res);
    }
  }
};

</script>

Seperti itu penggunaan Observable API untuk handle state management sendiri dan bisa dipakai di vue component manapun.

Sekian dulu dari saya and cheers!