12

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!

0

1 Answer 1

24

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

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

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

reactivity

Sign up to request clarification or add additional context in comments.

2 Comments

Hi - I tried that but I keep getting vue.common.js?e881:2964 Uncaught TypeError: exp.trim is not a function(…)
@user1547174 this is looks vue 1.x try this Vue.set(this.someObject, 'planes', true)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.