Home > Net >  Vue fetch variable from service file in components but should maintain its own state
Vue fetch variable from service file in components but should maintain its own state

Time:01-17

I have two components Component A and Component B and a service file which has all the constants constants.js

The constants.js file has a variable VMWARE_CONFIG

  VMWARE_CONFIG: [
    {
      name: "Production",
      selected: false,
      year: "1yr",
    },
    {
      name: "Development",
      selected: false,
      year: "1yr",
    }
 ]

This variable is being imported into Component A and Component B and is used a filter for further data processing

data() {
    return {
      priceList: null,
      search: null,
      mappedInstancesheader: Constants.MappedServerInstancesHeaders,
      unMappedServersheader: Constants.UnMappedServerInstancesHeaders,
      computeDetailsData: null,
      aws_migration_config: "all",
      slider: { label: "color", val: 25, color: "orange darken-3" },
      vmware_config: Constants.VMWARE_CONFIG,
      items: [],
    }
  }

The same code is being used in different components

The issue I am facing is that if user changes a filter on component A, it reflects on component B as well, I want to maintain different state for the variable for each components.

I can do one thing, to define the variable in each component itself but in reality this array object has more than 15 objects and is used in more than 3 components and there are 6 other variables with similiar use-case

CodePudding user response:

You can use Spread operators such as:

data() {
return {
  priceList: null,
  search: null,
  mappedInstancesheader: Constants.MappedServerInstancesHeaders,
  unMappedServersheader: Constants.UnMappedServerInstancesHeaders,
  computeDetailsData: null,
  aws_migration_config: "all",
  slider: { label: "color", val: 25, color: "orange darken-3" },
  vmware_config: [...Constants.VMWARE_CONFIG]
  items: [],
  }
}

For more information, click here

The problem is:
When you import or use an array, you refer to its location in memory.
Thus, when you use and change the array, you change the array that is stored in memory, so everywhere it is used, it will change, since it is the same array.

The solution is:
Duplicating the array in memory, i.e. creating another array
The easiest way to do this by ES6 is Spread operators.
But you can also use libraries like lodash cloneDeep

  • Related