11

I have following code

<script lang="ts">
import { RouterView } from "vue-router";
import defaultLayout from "@/layouts/default.vue";
import dashboardLayout from "@/layouts/dashboard.vue";
import { useDefaultStore } from "@/stores/default";
import "./index.css";
import { defineComponent } from "vue";
export default defineComponent({
  setup() {
    let { getLayout } = useDefaultStore();

    return { getLayout };
  },
  components: { defaultLayout, dashboardLayout },
});
</script>

<template>
  {{ getLayout }}
  <component :is="getLayout">
    <RouterView />
  </component>
</template>

When i got to /dashboard my state gets updated but the getter does not for some reason, why is that?

<script setup lang="ts">
import { useDefaultStore } from "@/stores/default";
let { getUserData, SET_LAYOUT, getLayout } = useDefaultStore();
SET_LAYOUT("dashboardLayout");
</script>

Here my store:

actions: {
    SET_LAYOUT(layout: any) {
      console.log("setting layout");
      console.log(layout);
      this.layout = layout;
    },
}

I literally can see the changes inside the console but they does not get applied on the UI

2 Answers 2

25

I have found it out.

You cannot destructure your store, it loses its reactivity

let { getLayout } = useDefaultStore();

So i changed it to

let store = useDefaultStore();

and used store.getLayout and it works!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I tripped up on this same issue! I assumed to maintain reactivity only the state needed storeToRefs to when destructuring the store. However, both state and getters need it. Actions work fine without it though.
This is one way to handle it. Another way is pointed out by Estus Flask's comment that lets you use destructuring while maintaining reactivity
14

This is covered by the documentation, this is the case for storeToRefs helper:

const { getLayout } = storeToRefs(useDefaultStore());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.