pinia with importmaps

by ksoncan34

HTML

<script type="importmap">
  {
    "imports": {
      "pinia": "https://cdn.jsdelivr.net/npm/pinia/dist/pinia.esm-browser.js",
      "vue-demi": "https://cdn.jsdelivr.net/npm/vue-demi/lib/v3/index.mjs",
      "@vue/devtools-api": "https://cdn.jsdelivr.net/npm/@vue/devtools-api/lib/esm/index.js",
      "vue": "https://cdn.jsdelivr.net/npm/vue/dist/vue.esm-browser.prod.js"
    }
  }
</script>
<div id="app">
<div> Count: {{ count }} </div>
<div> Watch Count: {{ watchCount }} </div>
<div> Count Ref: {{ countRef }} </div>
<div> Count Times Two: {{ countTimesTwo }} 
<div> Count Times Two Ref: {{ countTimesTwoRef }} 
 <div> Count Times Three: {{ countTimesThree() }} </div>
  <div> Count Times Four: {{ countTimesFour() }} </div>
  <div> Count Times Four Ref: {{ countTimesFourRef() }} </div>
  <button @click="incrementCount()">Increment Count</button>
</div>

JavaScript

// just needed for jsfiddle to detect module import
import * as vue from 'vue';

import {
  createPinia,
  defineStore,
  storeToRefs
} from 'pinia';

import {
  createApp,
  h,
  ref,
  computed, 
  watch
} from 'vue';


const useMyStore = defineStore('my', () => {
  const count = ref(1);  
  const count2 = ref(1);  
  
  return {
    count,
    count2,
    increment() {
      count.value++;      
      setTimeout(() => {
      	count2.value ++;
      }, 1000);
    }
  }
});

const useCalcStore = defineStore('calc', () => {
  const myStore = useMyStore();
  const countTimesTwo = computed(() => {
    // No NEED FOR REFS
    console.log('contTimeTwo Called');
    return myStore.count * 2;
  });
  return {
    countTimesTwo,
    countTimesThree() {
     // NO NEED FOR REFS
     console.log('contTimeThree Called');
     	return myStore.count2 * 3;
    }
  }
});

const app = createApp({
  setup() {
    // debugger;
    const watchCount = ref(1);
    const store = useMyStore();
    const calcStore = useCalcStore();
    
    watch(storeToRefs(store).count, () => {
      watchCount.value ++;
    });

    return {
      incrementCount: store.increment,
      watchCount: watchCount,
      count: store.count,
      countRef: storeToRefs(store).count, // REF REQUIRED
      countTimesTwo: calcStore.countTimesTwo,
      countTimesTwoRef: storeToRefs(calcStore).countTimesTwo,  // REF REQUIRED
      countTimesThree: calcStore.countTimesThree,
      countTimesFour () {
        return store.count * 4;
      },
      countTimesFourRef () {
        return storeToRefs(store).count.value * 4;
      }
      
    }
  }

}).use(createPinia())

app.mount('#app')