Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update data property / object in vue.js

is there a way I can programmatically update the data object / property in vue.js? For example, when my component loads, my data object is:

data: function () {
    return {
        cars: true,
    }
}

And after an event is triggered, I want the data object to look like:

data: function () {
    return {
        cars: true,
        planes: true
    }
}

I tried:

<script>

module.exports = {

    data: function () {
        return {
            cars: true
        }
    },

    methods: {
        click_me: function () {
            this.set(this.planes, true);
        }
    },

    props: []

}

</script>

But this gives me the error this.set is not a function. Can someone help?

Thanks in advance!

like image 713
Trung Tran Avatar asked Nov 06 '16 19:11

Trung Tran


People also ask

How do I update my Vue component?

The best way to force Vue to re-render a component is to set a :key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.

What is data property in VUE JS?

data: The data property value is an anonymous function which is returning object. Every property inside that object is added to the Vue reactivity system so that if we change that property value then vuejs re-renders the dom with the updated data.

Do props update Vue?

As long as you're updating a reactive property (props, computed props, and anything in data ), Vue knows to watch for when it changes. All we have to do is update count , and Vue detects this change. It then re-renders our app with the new value!


1 Answers

Vue does not allow dynamically adding new root-level reactive properties to an already created instance. However, it’s possible to add reactive properties to a nested object, So you may create an object and add a new property like that:

data: function () {
    return {
        someObject:{
            cars: true,
    }
}

and add the property with the set method:

methods: {
        click_me: function () {
            this.$set(this.someObject, 'planes', true)
        }
    }

for vue 1.x use Vue.set(this.someObject, 'planes', true)

reactivity

like image 53
ABDEL-RHMAN Avatar answered Oct 12 '22 13:10

ABDEL-RHMAN