0
votes

Currently, I'm using Vuex for managing application-level state.

I need to store data only within the Vue component lifecycle. Is it possible to use Vuex for storing local component states without involving the global store?

For example, I have a component like that:

class SomeComponent extends Vue {
  id = this.$props.componentId;
  localData = {};

  async created() {
    this.localData = await apiClient.getDataById(this.id);
  }
}

Then I can use components with different prop componentId, and every component should manage its own state.

<SomeComponent componentId="1" />
<SomeComponent componentId="2" />
<SomeComponent componentId="3" />

So ideal variant I'd like to see:

import LocalStore from './local-store';

class SomeComponent extends Vue {
  id = this.$props.componentId;
  localStore = new LocalStore(); // <- this is the Vuex store

  created() {
    localStore.getDataById(this.id);
  }
}
1

1 Answers

0
votes

yes, it is most definitely possible. i've never used the class-based syntax, but in object based syntax, it would look something like this

<div>
  <p>{{ state1 }}<p>
  <p>{{ state2 }}</p>
  <p>{{ localState }}</p>
</div>
export default {
  computed: {
    state1() {
      return this.$store.state.state1;
    }
    state2() {
      return this.$store.state.state2;
    }
  },
  data() {
    return {
       localState: 3
    }
  },
  props: {
    componentId: {
      type: Number
  },
}

again, ive never used the class base syntax, but it might look like this pseudocode

import { Prop } from 'vue-class-component'

export default class App extends Vue {
  get state1() {
    return this.$store.state.state1;
  }
  get state2() {
    return this.$store.state.state2;
  }

  localState = 3

  @Prop()
  componentId: Number
}