Vlad K.
Vlad K.

Reputation: 399

Vue.js how to change computed property from a method?

For example, I have a button that has a property :disabled="isDisabled" where isDisabled is a computed property that returns a Boolean. Also, in the code, I have a method from which I want to change the computed property value. For example, in the case of doing some operation (e.g sending a request to a server), I want to make a button inactive. But then I want to let the computed property doing their job in case any action would be applied in a range of its authority. So I want to explicitly redefine the value returned by the computed property.

<button
  type="submit"
  class="btn btn-primary"
  :disabled="isDisabled"
   @click.prevent="submitted"
>
computed: {
     isDisabled: function() {
     //... some code
     return true
     }
}

Which is the right way to solve this problem? Thank you.

Upvotes: 1

Views: 3645

Answers (1)

David L
David L

Reputation: 33863

As I mentioned in my comment, you typically want to have a computed property handle just one job. If you add a data property that specifically deals with your in-flight http request and use both, you get fine-grained control over your disabled state.

<button
  type="submit"
  class="btn btn-primary"
  :disabled="isDisabled || isLoading"
   @click.prevent="submitted"

data: function () {
    return {
        isLoading: false
    }
},
computed: {
     isDisabled: function() {
     //... some code
     return true
     }
},
methods: {
    makeHttpCall: function () {
        this.isLoading = true

        axios
            .get('url')
            .finally(function () {
                this.isLoading = false
            })
    }
}

Upvotes: 3

Related Questions