useAllowCreate.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var vue = require('vue');
  4. function useAllowCreate(props, states) {
  5. const createOptionCount = vue.ref(0);
  6. const cachedSelectedOption = vue.ref(null);
  7. const enableAllowCreateMode = vue.computed(() => {
  8. return props.allowCreate && props.filterable;
  9. });
  10. function hasExistingOption(query) {
  11. const hasValue = (option) => option.value === query;
  12. return props.options && props.options.some(hasValue) || states.createdOptions.some(hasValue);
  13. }
  14. function selectNewOption(option) {
  15. if (!enableAllowCreateMode.value) {
  16. return;
  17. }
  18. if (props.multiple && option.created) {
  19. createOptionCount.value++;
  20. } else {
  21. cachedSelectedOption.value = option;
  22. }
  23. }
  24. function createNewOption(query) {
  25. if (enableAllowCreateMode.value) {
  26. if (query && query.length > 0 && !hasExistingOption(query)) {
  27. const newOption = {
  28. value: query,
  29. label: query,
  30. created: true,
  31. disabled: false
  32. };
  33. if (states.createdOptions.length >= createOptionCount.value) {
  34. states.createdOptions[createOptionCount.value] = newOption;
  35. } else {
  36. states.createdOptions.push(newOption);
  37. }
  38. } else {
  39. if (props.multiple) {
  40. states.createdOptions.length = createOptionCount.value;
  41. } else {
  42. const selectedOption = cachedSelectedOption.value;
  43. states.createdOptions.length = 0;
  44. if (selectedOption && selectedOption.created) {
  45. states.createdOptions.push(selectedOption);
  46. }
  47. }
  48. }
  49. }
  50. }
  51. function removeNewOption(option) {
  52. if (!enableAllowCreateMode.value || !option || !option.created || option.created && props.reserveKeyword && states.inputValue === option.label) {
  53. return;
  54. }
  55. const idx = states.createdOptions.findIndex((it) => it.value === option.value);
  56. if (~idx) {
  57. states.createdOptions.splice(idx, 1);
  58. createOptionCount.value--;
  59. }
  60. }
  61. function clearAllNewOption() {
  62. if (enableAllowCreateMode.value) {
  63. states.createdOptions.length = 0;
  64. createOptionCount.value = 0;
  65. }
  66. }
  67. return {
  68. createNewOption,
  69. removeNewOption,
  70. selectNewOption,
  71. clearAllNewOption
  72. };
  73. }
  74. exports.useAllowCreate = useAllowCreate;
  75. //# sourceMappingURL=useAllowCreate.js.map