Vue 3 数组状态更改不会触发观察者

时间:2021-07-17 17:44:58

标签: vue.js vuejs3

我有一个表格,每行都有一个复选框,还有一个选择所有行的头部复选框,当任何复选框状态发生变化时,它应该触发一个事件,但由于某种原因,当我使用主复选框来选中它们时,在我取消选中它之前,观察者不会被触发:

模板:

<table>
 <thead>
  <tr>
   <th>
    <input
     type="checkbox"
     class="form-check-input widget-9-check"
     :name="name"
     v-model="areAllItemsSelected"
    />
   </th>
  </tr>
 </thead>
 <tbody>
  <tr v-for="..."> //here is rowIndex
   <td>
    <input
     type="checkbox"
     class="form-check-input widget-9-check"
     :value="rowIndex"
     v-model="selectedItems"
    />
   </td>
  </tr>
 </tbody>
</table>

设置:

setup(props, {emit}) {
    const selectedItems = ref([])
    const areAllItemsSelected = ref(false)

    watch(areAllItemsSelected, (newValue) => {
      if(newValue) {
        items.value.forEach((item, index) => {
          selectedItems.value.push(index) //this should trigger the below watcher
        })
      } else {
        selectedItems.value = []
      }

    })

    watch(selectedItems, (newValue) => { //this doesn't run when areAllItemsSelected is checked, only when is unchecked
      emit('itemSelected', newValue)
    })

    return {
      items,
      selectedItems,
      areAllItemsSelected
    }
  }

1 个答案:

答案 0 :(得分:2)

Vue 3 需要 deep watcher flag when watching arrays。在 <form [formGroup]="rowForm"> <div *ngIf="formArray" formArrayName="rows"> <div *ngFor="let rows of formArray.controls; let i = index" [formGroupName]="i"> <mat-checkbox class="example-margin" formControlName="checkbox2" name="checkbox2" (click)="toggleInput(i)">Show hidden option!</mat-checkbox> <mat-form-field class="example-full-width"> <input matInput placeholder="Input1" formControlName="input1" name="input1" required> </mat-form-field> <mat-form-field class="example-full-width"> <input matInput placeholder="Input2" formControlName="input2" name="input2" required> </mat-form-field> <mat-form-field *ngIf="inputVisibleMapper[i]" class="example-full-width"> <input matInput placeholder="Input3" formControlName="input3" name="input3" required> <mat-error>Title is required</mat-error> </mat-form-field> <button mat-button color="primary" *ngIf="formArray.length > 1" (click)="deleteRow(i)" class="btn btn-danger">Delete Button</button> </div> </div> <button mat-button color="primary" (click)="addNewRow()" class="btn btn-primary">Add new Row</button><br> </form> 的第三个参数中传递 deep 标志:

watch()

demo