Search code examples
typescriptvuejs3v-for

full selection checkbox button doen't work in vue3


I'm a noob for Vue3+typescript. I have a problem implementing full selection checkbox button, so I'm going to ask for advice. The function I want is as follows. 'checkbox-text-btn' custom component is listed as v-for (I referred to this. v-for Refs), and there is a check box with a full selection function on the parent. I hope that the child's check box will be applied according to the status of the parent's check box, and the parent's check box will be changed according to the status of the child's.

full code is here codesandbox-draft

<template>
  <table class="table">
    <tr>
      <th>
        <a style="padding: 3px">ALL</a>
        <input
          type="checkbox"
          v-bind="isCheckServerAll"
          @click="setCheckServerAll()"
        />
      </th>
      <td>
        <div id="serverlist">
          <checkbox-text-btn
            v-for="cacheServerInfo in cacheServerInfos"
            :key="cacheServerInfo.serverId"
            :btn-text="cacheServerInfo.cacheServerName"
            :ref="setItemRef($el)"
          ></checkbox-text-btn>
        </div>
      </td>
    </tr>
  </table>
</template>

I can't use computed property because of refs from v-for, so I moved logic as a method.

setup: {
 const isCheckServerAll = ref(false);
  const setCheckServerAll = () => {
    isCheckServerAll.value = !isCheckServerAll.value;
    for (let i = 0; i < itemRefs.length; i++) {
      itemRefs[i].checked = isCheckServerAll.value; // not apply to DOM
      //itemRefs[i].setCheck(value); // 'not a function error' occures
      console.log(itemRefs[i].checked);
    }
  };
}

By the way, the check value of the child changes, but it doesn't apply to DOM. I even called a function instead of changing the variable of my child directly, but in this case, the runtime outputs a 'not a function' error.

<script lang="ts">
import { defineComponent, ref } from "vue";

export default defineComponent({
  name: "CheckboxTextButton",
  props: ["btnText"],

  setup(props) {
    const checked = ref(false);

    const onClick = () => {
      checked.value = !checked.value;
    };

    const setCheck = (value) => {
      checked.value = value;
    };

    return {
      checked,
      onClick,
      setCheck,
    };
  },
});
</script>

Why full selection checkbox button doesn't work? And why is 'check' variable accessible and 'setCheck' method not?


Solution

  • Why don't you make a multicheckbox component into whom you pass an array of cacheServerInfo? The component could handle the state of the checkboxes internally. In that case you could still reuse your btn-checkbox-component. Also, it could be helpful for you to read up about the v-model directive.