Search code examples
vue.jsvuex

Watching a vuex state does not give me access to it's value


In my store.js, I have:

state: {
  User: false
},

I am not using getters and User will be an object once it's set. In my component, I have:

export default {
  name: "ConversationsList",
  mixins: [conversationMixin],
  computed: {
    ...mapState(["User"])
  },
  data: () => {
    return {
      conversations: false,
      datedConversations: false
    };
  },
  watch: {
    User: {
      immediate: true,
      handler(newVal, oldVal) {
        console.log(newVal, oldVal);

But newVal is not an object with simple properties. They appear to be functions: How can I access them as regular properties?

User object getters and setters


Solution

  • Access them just like ordinary properties:

    Access it in script:

    const email = User.email
    

    Access it in template:

    <template>
      <span>{{ User.email }}</span>
    </template>
    

    Vue applies getter and setter to each property, to implement it's reactivity. As you see from the code above, each property is initialised with it's getter and setter, so every time you change it, Vue can rerender the appropriate parts of your template.

    I would recommend you read about getters and setters.