user7665869
user7665869

Reputation: 29

how update data self in vue computed?

In my case, i want update data self in computed. like following example:

var example = new Vue({
    el: '#example',
    data: {
        Foo: []
    },
    computed: {
        Bar: {
            // getter
            get: function(){
                return 'data'
            },
            // setter
            set: function(newValue){
                this.Bar = newValue
            }
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="example">
    <p>Original message: "{{ Bar }}"</p>
</div>   
if i update Bar, like example.Bar = 'newBar', it will give me error message: Uncaught RangeError: Maximum call stack size exceeded

how update Bar in computed?

Upvotes: 0

Views: 2031

Answers (2)

Probably you mean this.Foo =?

        var example = new Vue({
            el: '#example',
            data: {
                Foo: []
            },
            computed: {
                Bar: {
                    // getter
                    get: function(){
                        return 'data'
                    },
                    // setter
                    set: function(newValue){
                        this.Foo = newValue
                    }
                }
            }
        })

You are trying to update value in updating value in updating value in ... That couse recursion.

Upvotes: 1

Estradiaz
Estradiaz

Reputation: 3573

Those getter setter are to be treated like proxies,

you need something to get from and something to set to.

A simple way to solve your issue is:

{
    el: '#example',
    data: {
        Foo: [],
        bar: 'data'
    },
    computed: {
        Bar: {
            // getter
            get: function(){
                return this.bar
            },
            // setter
            set: function(newValue){
                this.bar = newValue
            }
        }
    }
}

Upvotes: 1

Related Questions