index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { use } from '../utils';
  2. import { CheckboxMixin } from '../mixins/checkbox';
  3. const [sfc, bem] = use('checkbox');
  4. export default sfc({
  5. mixins: [CheckboxMixin('van-checkbox-group', bem)],
  6. computed: {
  7. checked: {
  8. get() {
  9. return this.parent ? this.parent.value.indexOf(this.name) !== -1 : this.value;
  10. },
  11. set(val) {
  12. if (this.parent) {
  13. this.setParentValue(val);
  14. } else {
  15. this.$emit('input', val);
  16. }
  17. }
  18. }
  19. },
  20. watch: {
  21. value(val) {
  22. this.$emit('change', val);
  23. }
  24. },
  25. methods: {
  26. toggle() {
  27. const checked = !this.checked;
  28. // When toggle method is called multiple times at the same time,
  29. // only the last call is valid.
  30. // This is a hack for usage inside Cell.
  31. clearTimeout(this.toggleTask);
  32. this.toggleTask = setTimeout(() => {
  33. this.checked = checked;
  34. });
  35. },
  36. onClickIcon() {
  37. if (!this.isDisabled) {
  38. this.toggle();
  39. }
  40. },
  41. onClickLabel() {
  42. if (!this.isDisabled && !this.labelDisabled) {
  43. this.toggle();
  44. }
  45. },
  46. setParentValue(val) {
  47. const { parent } = this;
  48. const value = parent.value.slice();
  49. if (val) {
  50. if (parent.max && value.length >= parent.max) {
  51. return;
  52. }
  53. /* istanbul ignore else */
  54. if (value.indexOf(this.name) === -1) {
  55. value.push(this.name);
  56. parent.$emit('input', value);
  57. }
  58. } else {
  59. const index = value.indexOf(this.name);
  60. /* istanbul ignore else */
  61. if (index !== -1) {
  62. value.splice(index, 1);
  63. parent.$emit('input', value);
  64. }
  65. }
  66. }
  67. }
  68. });