简体   繁体   中英

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!

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 thevm.$set method:

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

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

reactivity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM