[Vuejs]-Vuex set state object default as object in array in state

1👍

This is a common JavaScript problem. It’s not possible to refer to a property of an object that wasn’t defined yet.

This requires to have temporary variable that stores a reference to reused object:

const items = [/*...*/];

...
 state: {
     items,
     currentItem: items[0]
 }

This can be done in-place in less readable way with IIFE if the context isn’t suitable for temporary variables:

 ...
 state: (items) => ({
     items,
     currentItem: items[0]
 })([/*...*/])

2👍

You are looking for a computed value.

Vue.config.devtools = false;
Vue.config.productionTip = false;

var app = new Vue({
  el: '#app',
  data: {
    items: ["First Item", "Second Item"],
    index: 0
  },
  computed: {
    currentItem() {
      return this.items[this.index];
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  {{ currentItem }}
</div>

In a store you can use a getter to achieve the same thing.

  getters: {
    currentItem: state => {
      return state.items[state.index];
    }
  }

Leave a comment