2

Suppose you have this object in the state of the Vuex store:

const state = {
  profile: {
   name: "Bob",
   jobTitle: 'Baker',
   age: 38,
  }
}

In the Vue.js template you can access this object with a computed property like this:

<template>
    <p>Welcome {{ profile.name }}</p>
</template>

This works fine but requires the properties to be defined upfront. And when there is no logged on user each property of profile needs to be set to an empty string. Because when we set state.profile = null the Vue template will complain that it can't find the property name anymore.

What is the best way to handle a case like this? Would we need to iterate the object properties and set them all to a blank string or is there a better way of handling this?

Thank you for your help.

DarkLite1
  • 13,637
  • 40
  • 117
  • 214

1 Answers1

1

You could use a factory method that returns an empty profile object/model to initialize your state. Then you add a reset action to your VUEX store that re-initializes your profile state whenever you need it.

Look at THIS article. This explains the above in more detail.

gvdvenis
  • 56
  • 5
  • Thank you, that is some pretty clever stuff! The only disadvantage that I see is with regards to readability. You can't simply open the `state.js` file and see the properties. – DarkLite1 Apr 28 '20 at 10:37
  • You're not restricted to putting everything in one file if that's what you mean. You could separate your factory methods out in their own files. There's also a possibility to make use of VUEX Modules: https://vuex.vuejs.org/guide/modules.html. That allows you to split-up your VUEX store into different (feature related) sections. – gvdvenis Apr 28 '20 at 10:55
  • You're right! I'm still learning and didn't see it at first. But yes, I think this is the correct answer. Thanks again for the great tip :) – DarkLite1 Apr 28 '20 at 11:04