sesc360
sesc360

Reputation: 3255

Avoid adding reactive properties to a Vue instance or its root $data at runtime - declare it upfront in the data option.

I am a bit confused using VueJS2. I added a few variables to the data container for sending it to my API. That works fine but Vue is throwing me a warning/error message which I don't know how to solve:

Avoid adding reactive properties to a Vue instance or its root $data at runtime - declare it upfront in the data option.

var app = new Vue({
    el: '#app',
    data: {
        incidentReference: '',
        streetName: '',
        latitude: '',
        longitude: '',
        featureTypeId: 1,
        archived: 0
    },

    computed: {
        href() {
            return '#' + this.name.toLowerCase().replace(/ /g, '-');
        }
    },

    mounted: function () {
        this.getIncidents();
    },

    methods: {
        onSubmit() {
            axios.post('/api/v1/incidents', this.$data)
                .then(response => alert('Success'))
                .catch(error => {
                    console.log(error.response);
                })
        },

        getIncidents: function() {
            console.log('getIncidents');
            var self = this;
            axios.get('/api/v1/incidents').then(function(response) {
                // set data on vm
                console.log(response.data);
                var incidentsReceived = response.data.data.map(function (incident) {
                    return incident;
                });
                Vue.set(self, 'incidents', incidentsReceived);
            });
        }
    }
});

Upvotes: 10

Views: 23600

Answers (3)

vladimir
vladimir

Reputation: 15218

In the context of Jest & Vue Test Utils consider declaring data in component:

const Component = {
  // ..
  data() { return { abc: 'abc'; } }
};

const wrapper = mount(Component, { /*..*/ });

instead of

const Component = { /*..*/ };
const wrapper = mount(Component, { /*..*/ });

wrapper.setData({ abc: 'abc' });
await wrapper.vm.$nextTick();

Upvotes: 0

Muhammad Waqas Dilawar
Muhammad Waqas Dilawar

Reputation: 2322

In my case during unit testing using Jest, I was setting selected but didn't have on component so got this error.

  wrapper.setData({
  selected: recipients,
});

So created the property on component and then it's working fine.

Upvotes: 5

AldoRomo88
AldoRomo88

Reputation: 2076

You're creating a new reactive property on the response of your API

Vue.set(self, 'incidents', incidentsReceived);

Not sure if you misspelled property's name or forget to create that property. Just use an existing property on you data section

Vue.set(self, 'incidentReference', incidentsReceived); //change property name

or

data: {
    incidents: null, //or create this property
},  

Upvotes: 10

Related Questions