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

Pet*_*ada 2 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>
Run Code Online (Sandbox Code Playgroud)

设置:

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
    }
  }
Run Code Online (Sandbox Code Playgroud)

ton*_*y19 9

Vue 3deep在观察数组时需要观察者标志deep在第三个参数中传递标志watch()

watch(selectedItems, (newValue) => {/*...*/}, { deep: true })
                                                  
Run Code Online (Sandbox Code Playgroud)

演示