Search code examples
javascriptobjectvue.jsvuex

Saving Vuex State on mounted lifecycle


I'm trying to save the application's root state on mounted lifecycle of VueJS and freeze the copy in $root's data, and my attempt is as following,

  mounted() {
    this.globalState = this.$store.state;
  },
  data () {
    return {
      globalState: null
    }
  }

However this approach is updating globalState so I came up with another way to freeze it by using Object.freeze() but with no luck it keeps updating.

Also I've tried to copy the this.$store.state to a const variable and update globalState via it, but it also fails.

My last attempt is as following, I know it's an ugly code but please bear with it.

    let emptyObj = {};
    Object.defineProperty(emptyObj, 'globalState',{
        value: this.$store.state,
        enumerable: false,
        configurable: false,
        writable: false
      }
    );
    this.globalState = emptyObj.globalState;

My question is, how can I copy and freeze the initial state of the application and store it in single data?


Solution

  • Since you do not want reactivity on the copy of the state object its better to create a custom option in your components option instead of freezing the object in the data option.

    import {cloneDeep} from "lodash"
    
    export default{
        myGlobalState: null,
        mounted() {
            this.$options.myGlobalState = cloneDeep(this.$store.state);
        }
    }
    

    Your custom option can be accesed using vm.$options and is not reactive

    this.$options.myGlobalState