form-input.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import { computed, ref, watch, unref } from 'vue'
  2. import { useElFormItemInject } from './use-form'
  3. import {
  4. isEmpty,
  5. isNotEmpty,
  6. getLabelByValue,
  7. isObject,
  8. isArray,
  9. isNumber, getFieldValue, setFieldValue, getUsingConfig
  10. } from '@cip/utils/util'
  11. import { judgeUseFn } from '@cip/components/cip-form-item/util'
  12. import { getValueByTemplate } from '../cip-form-input/form-value-store'
  13. import { UpdateFormStream } from '../helper/update-form-stream'
  14. const useUpdateStream = (props, context) => {
  15. const updateStream = new UpdateFormStream(props, (val) => context.emit('streamUpdate:model', val))
  16. return updateStream
  17. }
  18. const useProxyOtherValue = (props, maxOtherKey = 1, updateStream) => {
  19. const result = []
  20. for (let i = 0; i < maxOtherKey; i++) {
  21. const proxyValue = computed({
  22. get () {
  23. return props.values[i + 1]
  24. },
  25. set (val) {
  26. updateStream.appendOtherValue(val, i + 1)
  27. updateStream.end()
  28. }
  29. })
  30. result.push(proxyValue)
  31. }
  32. return result
  33. }
  34. const useFormBasicConfig = (props) => {
  35. const securityConfig = computed(() => {
  36. return props.config ?? {}
  37. })
  38. const clearable = computed(() => {
  39. return securityConfig.value.clearable ?? true
  40. })
  41. const width = computed(() => {
  42. return securityConfig.value.width ?? '100%'
  43. })
  44. const placeholder = computed(() => {
  45. return securityConfig.value.placeholder ?? ' '
  46. })
  47. return {
  48. securityConfig, clearable, width, placeholder
  49. }
  50. }
  51. export const useFormInput = (props, context, { fromModelValue, toModelValue, maxOtherKey } = {}) => {
  52. const inputRef = ref()
  53. const updateStream = useUpdateStream(props, context)
  54. const { securityConfig, clearable, width, placeholder } = useFormBasicConfig(props)
  55. const emitInput = (val) => {
  56. emitModelValue(val)
  57. }
  58. const emitModelValue = (val) => {
  59. val = isNotEmpty(toModelValue) ? toModelValue(val) : val
  60. // 同时支持2中修改方式,在formItem中不在接受update:modelValue
  61. context.emit('update:modelValue', val)
  62. updateStream.appendValue(val)
  63. updateStream.end()
  64. }
  65. // 组件单独使用时不在支持对otherValue的修改
  66. const emitOtherValue = (val) => {
  67. // context.emit('update:otherValue', val)
  68. updateStream.appendOtherValue(val)
  69. updateStream.end()
  70. }
  71. const proxyOtherValue = useProxyOtherValue(props, maxOtherKey, updateStream)
  72. const proxyValue = computed({
  73. // 单值时使用
  74. get () {
  75. let modelValue = props.modelValue
  76. if (props.values && props.values.length > 0) {
  77. modelValue = props.values[0]
  78. }
  79. return isNotEmpty(fromModelValue) ? fromModelValue(modelValue) : modelValue // props.modelValue
  80. },
  81. set (val) {
  82. emitModelValue(val)
  83. }
  84. })
  85. watch([() => securityConfig.value.defaultValue, () => props.changeCount], ([defaultValue]) => {
  86. if (props.showTemplate === true) {
  87. // 处于展示模版模式时,同步展示默认值【注:此模式仅在设计表单时开启】
  88. emitInput(defaultValue)
  89. } else {
  90. // 处于实际值展示模式时, 需要modelValue 和defaultValue都不为空才进行值的更新
  91. if (isEmpty(props.modelValue) && isNotEmpty(defaultValue)) {
  92. // emitInput(getValueByTemplate(defaultValue)) // date下需要转换值后再写入
  93. proxyValue.value = getValueByTemplate(defaultValue)
  94. }
  95. }
  96. }, { immediate: true })
  97. return {
  98. inputRef,
  99. proxyValue,
  100. securityConfig,
  101. emitInput,
  102. emitModelValue,
  103. emitOtherValue,
  104. updateStream,
  105. proxyOtherValue,
  106. placeholder,
  107. clearable,
  108. width
  109. }
  110. }
  111. export const useFormView = (props, { maxOtherKey } = {}) => {
  112. const { securityConfig, clearable, width, placeholder } = useFormBasicConfig(props)
  113. const proxyOtherValue = useProxyOtherValue(props, maxOtherKey, () => { })
  114. return {
  115. securityConfig, clearable, width, placeholder, proxyOtherValue
  116. }
  117. }
  118. export const useElementFormEvent = () => {
  119. const elFormItem = useElFormItemInject()
  120. const handleChange = (val) => {
  121. elFormItem.formItemMitt?.emit('el.form.change', [val])
  122. }
  123. const handleBlur = (val) => {
  124. elFormItem.formItemMitt?.emit('el.form.blur', [val])
  125. }
  126. return {
  127. handleChange,
  128. handleBlur
  129. }
  130. }
  131. export const useOptions = (props, multiple, updateStream, context) => {
  132. const optionProps = computed(() => {
  133. return Object.assign({ label: 'label', value: 'value', children: 'children' }, props.config?.treeProps, props.config?.optionProps)
  134. })
  135. const otherKey = computed(() => {
  136. return props.config?.otherKey
  137. })
  138. const splitKey = computed(() => {
  139. return props.config?.splitKey ?? ','
  140. })
  141. const withObject = computed(() => {
  142. // 传出的值是否为object
  143. return props.config?.withObject ?? false
  144. })
  145. const realArray = computed(() => {
  146. // 需要返回的shu
  147. return props.config?.realArray ?? false
  148. })
  149. const options = ref([])
  150. let unwatch = null
  151. const getOptions = async (val, outVal) => {
  152. if (props.config.asyncOptions) {
  153. const asyncFunc = judgeUseFn('asyncOptions', props.config)
  154. options.value = await asyncFunc(val, outVal)
  155. } else {
  156. options.value = props.config?.options ?? []
  157. }
  158. if (unwatch) unwatch() // 获取一次options后重新开启监听
  159. unwatch = watch(() => props.changeCount, () => {
  160. if (isEmpty(props.modelValue) && props.config.autoSelect && updateStream) { // modelValue为空
  161. const autoValue = isObjectOption.value ? options.value[0][optionProps.value.value] : options.value[0]
  162. const autoLabel = isObjectOption.value ? options.value[0][optionProps.value.label] : options.value[0]
  163. // eslint-disable-next-line no-unused-expressions
  164. // emitInput(autoValue)
  165. // emitOtherValue && emitOtherValue(autoLabel)
  166. updateStream.appendValue(autoValue)
  167. updateStream.appendOtherValue(autoLabel)
  168. updateStream.end()
  169. }
  170. }, { immediate: true })
  171. }
  172. // 计算option类型
  173. const isObjectOption = computed(() => {
  174. return isObject(options.value[0])
  175. })
  176. // 获取otherValue的值
  177. const getOtherValueByValue = (value) => {
  178. if (unref(multiple)) {
  179. if (withObject.value) {
  180. return value.map(i => {
  181. return options.value?.find(v => v[optionProps.value.value] === i) ?? {}
  182. })
  183. }
  184. return value.map(val => getLabelByValue(val, options.value, optionProps.value) ?? val).join(splitKey.value)
  185. } else {
  186. if (withObject.value) {
  187. return options.value?.find(v => v[optionProps.value.value] === value) ?? {}
  188. }
  189. return getLabelByValue(value, options.value, optionProps.value) ?? value
  190. }
  191. }
  192. const getValue = (modelValue) => {
  193. if (unref(multiple)) {
  194. // 防止空字符串导致的['']错误
  195. const modelArray = isArray(modelValue) ? modelValue : (modelValue ? modelValue.split(splitKey.value) : [])
  196. // 如果option的value值是数字型将值转换为数字型,否则就是字符型
  197. const autoFormat = !(props.config?.multiple && props.config?.remote)
  198. if (autoFormat) {
  199. const optionCell = isObjectOption.value ? options.value[0]?.[optionProps.value.value] : options.value[0]
  200. if (isNumber(optionCell)) {
  201. return modelArray.map(i => parseInt(i))
  202. } else {
  203. return modelArray.map(i => String(i))
  204. }
  205. }
  206. return modelArray
  207. } else {
  208. return modelValue ?? ''
  209. }
  210. }
  211. const getModelValue = (value) => {
  212. if (unref(multiple)) {
  213. if (realArray.value) {
  214. return value
  215. } else {
  216. return isArray(value) ? value.join(splitKey.value) : value
  217. }
  218. } else {
  219. return value
  220. }
  221. }
  222. // 根据otherValue跟随modelValue变化
  223. const getOtherValue = (modelValue, value) => {
  224. if (isObjectOption.value) {
  225. return getOtherValueByValue(value)
  226. } else {
  227. return modelValue
  228. }
  229. }
  230. if (!(props.config.dependOn?.length) && !(props.config.outDependOn?.length)) {
  231. getOptions() // .then(() => { console.log('[init]: getOptions') })
  232. if (props.config.options) { // 动态表单设计时修改options需要触发此方法
  233. watch(() => props.config.options, (val) => {
  234. getOptions() // .then(() => { console.log('[config.options change]: getOptions') })
  235. })
  236. }
  237. } else {
  238. watch([() => props.dependOnValues, () => props.outDependOnValues], ([dependOnValues, outDependOnValues]) => {
  239. getOptions(dependOnValues || {}, outDependOnValues || {}) // .then(() => { console.log('[dependOn change]: getOptions') })
  240. }, { immediate: true })
  241. }
  242. // options部分组件重新定义proxyOptionsValue
  243. const proxyOptionsValue = computed({
  244. get () {
  245. return getValue(props.modelValue)
  246. },
  247. set (value) {
  248. const modelValue = getModelValue(value)
  249. if (context) {
  250. context.emit('update:modelValue', modelValue)
  251. }
  252. if (updateStream) {
  253. updateStream.appendValue(modelValue)
  254. if (otherKey.value) {
  255. const otherValue = getOtherValue(modelValue, value)
  256. // context.emit('update:otherValue', otherValue)
  257. updateStream.appendOtherValue(otherValue)
  258. // 目前仅支持单选
  259. if (!unref(multiple)) {
  260. const checkOption = options.value.find(v => v[optionProps.value.value] === value)
  261. updateStream.appendOtherValue(checkOption, 2)
  262. } else {
  263. const checkOptions = options.value.filter(v => value.includes(v[optionProps.value.value]))
  264. updateStream.appendOtherValue(checkOptions, 2)
  265. }
  266. }
  267. updateStream.end()
  268. } else {
  269. console.error('updateStream 不存在,无法更新数据')
  270. }
  271. }
  272. })
  273. return {
  274. optionProps,
  275. options,
  276. getOptions,
  277. isObjectOption,
  278. getValue,
  279. getModelValue,
  280. getOtherValue,
  281. proxyOptionsValue
  282. }
  283. }
  284. /**
  285. * 从props.config去除制定的值
  286. * propKeys事例:
  287. * [
  288. * 'a', 获取A
  289. * ['b','b1'], 获取b的值转为b1
  290. * ['c',{key:'c1', defaultValue: 1}], 获取c的值转为c1若c的值不存在则赋值1
  291. * ['d',{ defaultValue: 1}] 获取d的若d不存在则赋值1
  292. * ]
  293. * @param props
  294. * @param propKeys
  295. *
  296. */
  297. export const useInputProps = (props, propKeys = []) => {
  298. return computed(() => {
  299. const config = props.config || {}
  300. return propKeys.reduce((acc, key) => {
  301. if (typeof key !== 'string') {
  302. const getKey = key[0]
  303. let setKey = key[0]
  304. let defaultValue
  305. if (isNotEmpty(key[1])) {
  306. if (typeof key[1] === 'string') {
  307. setKey = key[1]
  308. } else {
  309. setKey = getUsingConfig(key[1].key, key[0]) // 只存在defaultValue配置时使用第一位key
  310. defaultValue = key[1].defaultValue
  311. }
  312. }
  313. const propValue = getFieldValue(config, getKey)
  314. setFieldValue(acc, setKey, getUsingConfig(propValue, defaultValue))
  315. } else {
  316. const propValue = getFieldValue(config, key)
  317. setFieldValue(acc, key, propValue)
  318. }
  319. return acc
  320. }, {}) || {}
  321. })
  322. }