Problem description

In Mounted, change the value of the checkbox, expecting the change event to occur, but it does not.

<template>
	   <el-checkbox v-model="checkBox" @change="change">test</el-checkbox>
</template>
<script>
  export default{
  	data() {
      return {
        checkBox: false,}},methods: {change(){
      	console.log('Changed value')}},mounted(){
    	this.checkBox = true}}</script>
Copy the code

Process of cause inquiry

Reference: blog.csdn.net/tangran0526…

Is it a BUG with the V-Model?

www.yuque.com/nicander/mp…

Now let’s go back to the problem I encountered: after clicking the button and directly changing the value of flag with JS, the checkbox status changed, but the change event was not triggered

The v-model has completed its mission. The v-model has completed its mission.

Presumably, the problem is not with VUE, but with native JS and HTML!

Bold assumption

My guess: using js to modify the Checked property of the checkbox will not trigger the change event

Code:

<body>
	<section id="app">
		<button onclick="alterCheckboxValue()">Switch!</button>
		<input type="checkbox" id="checkbox1" onchange="handleChange()">
	</section>
	<script>
		function alterCheckboxValue() {
			const el = document.querySelector("#checkbox1"); el.checked = ! el.checked; }function handleChange(e) {
			console.log("Trigger change event");
		}
	</script>
</body>
Copy the code

The results, shown below, confirm the conjecture:

conclusion

Changing the checked property of the checkbox with js does not trigger the change event

If you want to monitor the checkbox change comprehensively, you can only:

  • User operationschange Event listeners
  • When you modify with JS, you write the handler function behind

Check the el-checkbox source code

Version: element-UI “: “^2.15.6

Looking at the source code, you can see that the handleChange event is not triggered when the value of the binding changes

watch: {
  // The binding value of el-checkbox
      value(value) {
        this.dispatch('ElFormItem'.'el.form.change', value); }}Copy the code

To solve

Re-encapsulate the el-CheckBox, add vaule’s listening property, and trigger the change event

<template>
  <el-checkbox v-model="value"></el-checkbox>
</template>

<script>
export default {
  name: 'my-checkBox'.props: {
    value: Boolean | String.change: {
      type: Function.default: () = >{}}},watch: {
    value() {
      console.log(this.value)
      this.$emit('change'.this.value)
    }
  }
}
</script>
Copy the code