N
N
Nikita Kit2018-02-20 13:11:41
JavaScript
Nikita Kit, 2018-02-20 13:11:41

How to correctly add data to initial state Vue.data from axios response?

I set the initial state of the data to the root Vue instance

data:function(){ return {
        Config: {},
        list: [],
        activeService: ''
      }},

Using the created hook, I request json from the server - it contains an object. In the csrf config, in list is an array of objects, json corresponds to the initial states in the data callback.
created: function(){
        axios.get("/jsondata/stepdata/step-1.json")
        .then(function(response){
          rootVueSteplist.$data = response.data;
        })
      }

I catch an error: Avoid replacing instance root $data. Use nested data properties instead.
Okay, really - I'm just trying to create a link to an object ... I'm doing it differently.
created: function(){
        axios.get("/jsondata/stepdata/step-1.json")
        .then(function(response){
          rootVueSteplist.$data = Object.assign(rootVueSteplist.$data, response.data)
        })
      }

And I'm getting the error again. The same one. It became more interesting - I experimented further.
This works:
created: function(){
        axios.get("/jsondata/stepdata/step-1.json")
        .then(function(response){
          rootVueSteplist.$data.Config = response.data.Config;
          rootVueSteplist.$data.list = response.data.list;
        })
      }

But this is shitty code. Does anyone know what the problem is? Googling vuejs errors is just mind blowing
UPD: Tried using the set method of a vue instance and was sent a longer error:
created: function(){
        axios.get("/jsondata/stepdata/step-1.json")
        .then(function(response){
          rootVueSteplist.$set(rootVueSteplist.$data, response.data)
          // rootVueSteplist.$data = Object.assign(rootVueSteplist.$data, response.data)
        })

Either I'm dumb, or I'm shit....
Avoid adding reactive properties to a Vue instance or its root $data at runtime - declare it upfront in the data option

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-02-20
@ShadowOfCasper

rootVueSteplist.$data = Object.assign(rootVueSteplist.$data, response.data)

Assignment is not required. Object.assign modifies the object passed as the first argument. That is, quite simply
Object.assign(rootVueSteplist.$data, response.data)

I
imhuman, 2018-02-20
@imhuman

Well, you can't directly assign a new value to $data at runtime. Make some property inside $data and throw the answer into it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question