【问题标题】:Vue 3 Array state change doesn't trigger watcherVue 3 数组状态更改不会触发观察者
【发布时间】:2021-07-18 21:41:49
【问题描述】:

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

模板:

<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
    }
  }

【问题讨论】:

    标签: vue.js vuejs3


    【解决方案1】:

    Vue 3 需要deep watcher flag when watching arrays。在watch() 的第三个参数中传递deep 标志:

    watch(selectedItems, (newValue) => {/*...*/}, { deep: true })
                                                      ?
    

    demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      • 2015-12-30
      • 2021-08-15
      • 2020-08-09
      • 2016-02-07
      相关资源
      最近更新 更多