1

In the following code:

https://jsfiddle.net/willywg/2g7m5qy5/

the button is disabled based on the state of the checkbox.

But when I change:

  computed: {
    isDisabled: function(){
        return !this.terms;
    }
  }

to

  methods: {
    isDisabled: function(){
        return !this.terms;
    }
  }

the enabling / disabling no longer works.

Why is this?

According to the documentation:

https://v2.vuejs.org/v2/guide/computed.html

shouldn't both work the same in this example?

tony19
  • 125,647
  • 18
  • 229
  • 307
Mary
  • 1,005
  • 2
  • 18
  • 37
  • because computed is reactive, methods are not. if using methods in this case you need to call that methods every time you check/un-check the input. – Timothy Lee Oct 25 '18 at 06:14

2 Answers2

1

Computed properties look for changes but methods need to be called with something like @change or @click for example. In this case, you can actually just bind your data object without either.

<div id="app">
  <p>
    <label for='terms'>
      <input id='terms' type='checkbox' v-model='terms' /> I accept terms!!!
    </label>
  </p>
  <button :disabled='!terms'>Send Form</button>
</div>

new Vue({
  el: '#app',
  data: {
    terms: false
  }
})
Dan
  • 36
  • 5
0

Computed and Methods are two different thing

method: call when you wan to do sth, like call an action/mutation or do something other than dealing with store/state

computed: you can use returned value to bind sth in template html, some changing value that changes according to some computations. If it wont change then just bind it to a date/state

In your current script computed locating isDisabled data change all the time . so whenever your data is changing its function triggering automatically.

But, if you want this in methods then you should trigger the function manually. Example:

<input id='terms' type='checkbox' v-model='terms' @change="isDisabled" /> I accept terms!!!

it will call isDisabled method when it will change.

For more details Methods vs Computed. Thanks

Emtiaz Zahid
  • 2,645
  • 2
  • 19
  • 35