1. 程式人生 > 其它 >全部設定為僅檢視/可編輯【第二種方法:watch+methods】

全部設定為僅檢視/可編輯【第二種方法:watch+methods】

<template>
  <div class="my-radio">
    <ul>
      <li v-for="item in list" :key='item.id'>
        <div class="name">
          <span>{{item.userName}}</span>
        </div>
        <van-radio-group v-model="item.operationType" direction="horizontal"
> <van-radio :name="1">僅檢視 <template #icon="props"> <div :class="props.checked ? 'activeIcon' : 'inactiveIcon'"><span></span></div> </template> </van-radio> <van-radio :name="2">可編輯
<template #icon="props"> <div :class="props.checked ? 'activeIcon' : 'inactiveIcon'"><span></span></div> </template> </van-radio> </van-radio-group> </li> </ul> <div class="set-all"> <
van-checkbox v-model='allReadonly' @click="handleAllReadonly">全部設定為僅檢視 <template #icon="props"> <div :class="props.checked ? 'activeIcon' : 'inactiveIcon'"><span></span></div> </template> </van-checkbox> <van-checkbox v-model='allEditable' @click="handleAllEditable">全部設定為可編輯 <template #icon="props"> <div :class="props.checked ? 'activeIcon' : 'inactiveIcon'"><span></span></div> </template> </van-checkbox> </div> </div> </template> <script> export default { data() { return { list: [ { id: 266, operationType: 2, userName: 'brandotest3' }, { id: 267, operationType: 1, userName: 'brandotest4' }, { id: 268, operationType: 2, userName: 'brandotest5' }, { id: 269, operationType: 2, userName: 'brandotest6' } ], allReadonly: false, allEditable: false } }, methods: { handleAllReadonly() { this.list.forEach((item) => { this.$set(item, 'operationType', 1) }) this.allReadonly = true this.allEditable = false }, handleAllEditable() { this.list.forEach((item) => { this.$set(item, 'operationType', 2) }) this.allReadonly = false this.allEditable = true } }, watch: { list: { handler(newList) { const arr = newList.map((item) => item.operationType) const allReadonly = arr.every((item) => item === 1) const allEditable = arr.every((item) => item === 2) if (allReadonly) { this.allReadonly = true } else if (allEditable) { this.allEditable = true } else { this.allReadonly = false this.allEditable = false } }, deep: true, immediate: true } } } </script>

沒有使用van-radio-group,將v-model直接繫結到van-checkbox,通過watch可以監聽到list的變化從而改變底部兩個按鈕的狀態。

但是底部兩個按鈕的狀態需要新增點選事件去改變list中的狀態