steros
steros

Reputation: 1924

how to watch multiple values or data change generically

I have this in a component. As you can see I'm watching for changes and then run an update function to update the database via an api call. Is there a way to strip the duplicate code and just watch for data changes in general? Or combine watching for several values.

watch: {
    mutable_threshold_value: function(val, oldVal) {
        this.update();
    },
    mutable_minimal_margin_fixed_value: function(val, oldVal) {
        this.update();
    },
    mutable_value_percentage: function(val, oldVal) {
        this.update();
    },
},
methods: {
    update: function() {
        this.$http.patch('/api/v1.0/margin-steps/' + this.id, {
            params: {
                threshold_value: this.mutable_threshold_value,
                minimal_margin_fixed_value: this.mutable_minimal_margin_fixed_value,
                value_percentage: this.mutable_value_percentage
            }
        });
    },

Upvotes: 1

Views: 598

Answers (1)

Sumurai8
Sumurai8

Reputation: 20737

Assemble treshold_value, minimal_margin_fixed_value and value_percentage into a computed property payload. This payload is what you send to the api. Because of how computed properties work, the computed property watches the variables it depends on. If they change, the payload changes, and thus the watcher is called. Watch this new payload variable instead and send the payload to the server whenever it changes.

computed: {
    payload () {
        return {
            threshold_value: this.mutable_threshold_value,
            minimal_margin_fixed_value: this.mutable_minimal_margin_fixed_value,
            value_percentage: this.mutable_value_percentage
        }
    }
},
watch: {
    payload () {
        this.update();
    }
},
methods: {
    update: function() {
        this.$http.patch('/api/v1.0/margin-steps/' + this.id, {
            params: this.payload
        });
    },
}

Upvotes: 4

Related Questions