Checkbox doesnt unchecked if it is checked initially in element-plus

68 views Asked by At

I have checkbox using element-plus:

<el-checkbox
  v-model="slotProps.action.check_control"
  :checked="slotProps.action.check_control"
  size="large"
  class="ml-4"
  :id="slotProps.action.id"
  @change="checkControl(slotProps.action.id, slotProps.action.check_control)"
/>

And I make api call with this function: checkControl.

const checkControl = (id, controlled) => {
  loading.value = true
  if (controlled === true) {
    controlled = 1
  } else {
    controlled = 0
  }
  ApiService.postTest('api...', {
    jar_id: id,
    check_control: controlled
  })
    .then((res) => {
      loading.value = false
    })
    .catch((e) => {
      loading.value = false
      console.log(e)
    })
}

whats wrong is after the page is rendered, if the checkbox is checked, I click the checkbox, but it checks it again instead of unchecked.

I am not sure if this related with element plus, but here is the documentation about it: https://element-plus.org/en-US/component/checkbox.html#checkbox-attributes

1

There are 1 answers

0
tao On
<input
  type="checkbox"
  v-model="foo"
/>

is short for

<input
  type="checkbox""
  :checked="foo"
  @change="(e) => { foo = e.target.checked }"
/>

See form input bindings.
In the above example, foo should be reactive.

Meaning: "do not use both v-model and :checked on same <input type="checkbox" />!"

If removing :checked doesn't solve the problem, please provide more detail about how slotProps.action.check_control gets populated in the context of your component. Currently, the js logic you are showing does not seem related to what you're passing to the <input />.


To set the checked value of the <input /> programatically, use only v-model and set whatever v-model points to as true, initially.