John Kohlmeier
John Kohlmeier

Reputation: 87

How to import Arrays from my Vue Components to store.js (State management with Vuex)

Good evening guys. :) I've got a small Problem. I simply have created an Array in a Stocks Vue Component which I made and now I want to Import the Array in my store.js file where I centralized all the necessary data (Vuex).

If there are any more Questions, just ask me. ^^

store.js file where the Array should get imported in

Stocks.vue file where there is the array

Upvotes: 0

Views: 751

Answers (3)

kano
kano

Reputation: 5926

Nathan's suggestion is a right one (and the Vue way to approach this). One small thing to consider though - what's the benefit of moving that data to your state? It adds complexity and unless other components also need access to it (and you can't pass it down via props), there's no real reason to move data out from a component-level. Not all app's state/data has to be centralized in your state-management system (vuex in this case).

If, however, the data should be globally (app-wide) accessible, then you should declare the stocks array already state-side and in your component Stocks.vue simply map the state:

// store.js
export const store = new Vuex.store({
  state: {
    funds: 10000,
    stocks: [
      // Stocks data goes here
    ]
  },
  // ...
})

And then map it in your component:

// Stocks.vue
<script>
  import { mapState } from 'vuex'

  export default {
    name: 'stocks',
    computed: {
      ...mapState({
        stocks: state => state.stocks
      })
    }
  }
</script>

You can now access stocks in Stocks.vue in your template block or this.stocks in your script block (e.g. under a method).

PS! Welcome to StackOverflow : )

Upvotes: 1

Nathan Boaldin
Nathan Boaldin

Reputation: 315

where i centralized all the neccessary data (Vuex).

If you want the array in your store why don't you initialize it there instead of your Stocks.vue component? I can't tell much about your app with just a .png. Is there a specific reason you cannot start with the array in the store?

If you had to leave it this way you could set a null value in your store. Something like:

state: {
  funds: 10000,
  stocks: null
}

Then write a mutation:

mutations: {
  SET_STOCKS (state, payload) {
    state.stocks = payload;
  }
}

Then you could commit the mutation in your component where the payload would be the value of your array. You can get around using mutations by manipulating the state object directly, but it is not recommended.

Upvotes: 1

Daniel Georgiev
Daniel Georgiev

Reputation: 41

Have you checked the documentation?

The basic idea you need to import the store from the component in which you want to read the store.

Upvotes: 0

Related Questions