D
D
danilr2020-02-24 08:07:25
Vue.js
danilr, 2020-02-24 08:07:25

How to correctly set the initial state of a component from Vuex?

I need to take data from Vuex when initializing components, then change it inside the components, and then update it in Vuex if necessary.
A simple first question - if I need the initial structure of a variable, is it correct to set it like this in Vuex?

export default new Vuex.Store({
  state: {
    currentNote: {
      id: 1,
      title: '',
      list: [
        {
          isDone: false,
          text: "",
          id: 1
        }
      ]
    }
  },

The second main question is if I need to set the initial data from Vuex in the component, in my case, an array from currentNod, how to do it right?
I skimmed and applied the slice() method so that it would give me a copy, otherwise, if without slice, then changing the data in the component, it changed them in the store.
export default {
  data() {
    const {currentNote, currentListId} = this.$store.state;

    return {
      title: currentNote.title,
      items: currentNote.list.slice(),
    };
  },

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2020-02-24
@danilr

Why I copy the data for the component is so that for every input change in the component - not to be processed on the Vuex side

For such cases, there is debounce
. The simplest way to copy an object recursively is:
const copy = JSON.parse( JSON.stringify( source ) )

Well, save is to call action and pass your copy to it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question