You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

386 lines
16 KiB

2 months ago
  1. <template>
  2. <view class="u-input" :class="inputClass" :style="[wrapperStyle]">
  3. <view class="u-input__content">
  4. <view
  5. class="u-input__content__prefix-icon"
  6. v-if="prefixIcon || $slots.prefix"
  7. >
  8. <slot name="prefix">
  9. <u-icon
  10. :name="prefixIcon"
  11. size="18"
  12. :customStyle="prefixIconStyle"
  13. ></u-icon>
  14. </slot>
  15. </view>
  16. <view class="u-input__content__field-wrapper" @tap="clickHandler">
  17. <!-- 根据uni-app的input组件文档H5和APP中只要声明了password参数(无论true还是false)type均失效此时
  18. 为了防止type=number时又存在password属性type无效此时需要设置password为undefined
  19. -->
  20. <input
  21. class="u-input__content__field-wrapper__field"
  22. :style="[inputStyle]"
  23. :type="type"
  24. :focus="focus"
  25. :cursor="cursor"
  26. :value="innerValue"
  27. :auto-blur="autoBlur"
  28. :disabled="disabled || readonly"
  29. :maxlength="maxlength"
  30. :placeholder="placeholder"
  31. :placeholder-style="placeholderStyle"
  32. :placeholder-class="placeholderClass"
  33. :confirm-type="confirmType"
  34. :confirm-hold="confirmHold"
  35. :hold-keyboard="holdKeyboard"
  36. :cursor-spacing="cursorSpacing"
  37. :adjust-position="adjustPosition"
  38. :selection-end="selectionEnd"
  39. :selection-start="selectionStart"
  40. :password="password || type === 'password' || false"
  41. :ignoreCompositionEvent="ignoreCompositionEvent"
  42. @input="onInput"
  43. @blur="onBlur"
  44. @focus="onFocus"
  45. @confirm="onConfirm"
  46. @keyboardheightchange="onkeyboardheightchange"
  47. />
  48. </view>
  49. <view
  50. class="u-input__content__clear"
  51. v-if="isShowClear"
  52. @click="onClear"
  53. >
  54. <u-icon
  55. name="close"
  56. size="11"
  57. color="#ffffff"
  58. customStyle="line-height: 12px"
  59. ></u-icon>
  60. </view>
  61. <view
  62. class="u-input__content__subfix-icon"
  63. v-if="suffixIcon || $slots.suffix"
  64. >
  65. <slot name="suffix">
  66. <u-icon
  67. :name="suffixIcon"
  68. size="18"
  69. :customStyle="suffixIconStyle"
  70. ></u-icon>
  71. </slot>
  72. </view>
  73. </view>
  74. </view>
  75. </template>
  76. <script>
  77. import { props } from "./props.js";
  78. import { mpMixin } from '../../libs/mixin/mpMixin';
  79. import { mixin } from '../../libs/mixin/mixin';
  80. import { debounce } from '../../libs/function/debounce';
  81. import { addStyle, addUnit, deepMerge, formValidate, $parent, sleep, os } from '../../libs/function/index';
  82. /**
  83. * Input 输入框
  84. * @description 此组件为一个输入框默认没有边框和样式是专门为配合表单组件u-form而设计的利用它可以快速实现表单验证输入内容下拉选择等功能
  85. * @tutorial https://uview-plus.jiangruyi.com/components/input.html
  86. * @property {String | Number} value 输入的值
  87. * @property {String} type 输入框类型见上方说明 默认 'text'
  88. * @property {Boolean} fixed 如果 textarea 是在一个 position:fixed 的区域需要显示指定属性 fixed true兼容性微信小程序百度小程序字节跳动小程序QQ小程序 默认 false
  89. * @property {Boolean} disabled 是否禁用输入框 默认 false
  90. * @property {String} disabledColor 禁用状态时的背景色 默认 '#f5f7fa'
  91. * @property {Boolean} clearable 是否显示清除控件 默认 false
  92. * @property {Boolean} password 是否密码类型 默认 false
  93. * @property {String | Number} maxlength 最大输入长度设置为 -1 的时候不限制最大长度 默认 -1
  94. * @property {String} placeholder 输入框为空时的占位符
  95. * @property {String} placeholderClass 指定placeholder的样式类注意页面或组件的style中写了scoped时需要在类名前写/deep/ 默认 'input-placeholder'
  96. * @property {String | Object} placeholderStyle 指定placeholder的样式字符串/对象形式"color: red;"
  97. * @property {Boolean} showWordLimit 是否显示输入字数统计只在 type ="text"或type ="textarea"时有效 默认 false
  98. * @property {String} confirmType 设置右下角按钮的文字兼容性详见uni-app文档 默认 'done'
  99. * @property {Boolean} confirmHold 点击键盘右下角按钮时是否保持键盘不收起H5无效 默认 false
  100. * @property {Boolean} holdKeyboard focus时点击页面的时候不收起键盘微信小程序有效 默认 false
  101. * @property {Boolean} focus 自动获取焦点 H5 平台能否聚焦以及软键盘是否跟随弹出取决于当前浏览器本身的实现nvue 页面不支持需使用组件的 focus()blur() 方法控制焦点 默认 false
  102. * @property {Boolean} autoBlur 键盘收起时是否自动失去焦点目前仅App3.0.0+有效 默认 false
  103. * @property {Boolean} disableDefaultPadding 是否去掉 iOS 下的默认内边距仅微信小程序且type=textarea时有效 默认 false
  104. * @property {String Number} cursor 指定focus时光标的位置 默认 -1
  105. * @property {String Number} cursorSpacing 输入框聚焦时底部与键盘的距离 默认 30
  106. * @property {String Number} selectionStart 光标起始位置自动聚集时有效需与selection-end搭配使用 默认 -1
  107. * @property {String Number} selectionEnd 光标结束位置自动聚集时有效需与selection-start搭配使用 默认 -1
  108. * @property {Boolean} adjustPosition 键盘弹起时是否自动上推页面 默认 true
  109. * @property {String} inputAlign 输入框内容对齐方式 默认 'left'
  110. * @property {String | Number} fontSize 输入框字体的大小 默认 '15px'
  111. * @property {String} color 输入框字体颜色 默认 '#303133'
  112. * @property {Function} formatter 内容式化函数
  113. * @property {String} prefixIcon 输入框前置图标
  114. * @property {String | Object} prefixIconStyle 前置图标样式对象或字符串
  115. * @property {String} suffixIcon 输入框后置图标
  116. * @property {String | Object} suffixIconStyle 后置图标样式对象或字符串
  117. * @property {String} border 边框类型surround-四周边框bottom-底部边框none-无边框 默认 'surround'
  118. * @property {Boolean} readonly 是否只读与disabled不同之处在于disabled会置灰组件而readonly则不会 默认 false
  119. * @property {String} shape 输入框形状circle-圆形square-方形 默认 'square'
  120. * @property {Object} customStyle 定义需要用到的外部样式
  121. * @property {Boolean} ignoreCompositionEvent 是否忽略组件内对文本合成系统事件的处理
  122. * @example <u-input v-model="value" :password="true" suffix-icon="lock-fill" />
  123. */
  124. export default {
  125. name: "u-input",
  126. mixins: [mpMixin, mixin, props],
  127. data() {
  128. return {
  129. // 清除操作
  130. clearInput: false,
  131. // 输入框的值
  132. innerValue: "",
  133. // 是否处于获得焦点状态
  134. focused: false,
  135. // value是否第一次变化,在watch中,由于加入immediate属性,会在第一次触发,此时不应该认为value发生了变化
  136. firstChange: true,
  137. // value绑定值的变化是由内部还是外部引起的
  138. changeFromInner: false,
  139. // 过滤处理方法
  140. innerFormatter: value => value
  141. };
  142. },
  143. created() {
  144. // 格式化过滤方法
  145. if (this.formatter) {
  146. this.innerFormatter = this.formatter;
  147. }
  148. },
  149. watch: {
  150. modelValue: {
  151. immediate: true,
  152. handler(newVal, oldVal) {
  153. // console.log(newVal, oldVal)
  154. if (this.changeFromInner || this.innerValue === newVal) {
  155. this.changeFromInner = false; // 重要否则会出现双向绑定失效问题https://github.com/ijry/uview-plus/issues/419
  156. return;
  157. }
  158. this.innerValue = newVal;
  159. // 在H5中,外部value变化后,修改input中的值,不会触发@input事件,此时手动调用值变化方法
  160. if (
  161. this.firstChange === false &&
  162. this.changeFromInner === false
  163. ) {
  164. this.valueChange(this.innerValue, true);
  165. } else {
  166. // 尝试调用up-form的验证方法
  167. if(!this.firstChange) formValidate(this, "change");
  168. }
  169. this.firstChange = false;
  170. // 重置changeFromInner的值为false,标识下一次引起默认为外部引起的
  171. this.changeFromInner = false;
  172. }
  173. }
  174. },
  175. computed: {
  176. // 是否显示清除控件
  177. isShowClear() {
  178. const { clearable, readonly, focused, innerValue } = this;
  179. return !!clearable && !readonly && !!focused && innerValue !== "";
  180. },
  181. // 组件的类名
  182. inputClass() {
  183. let classes = [],
  184. { border, disabled, shape } = this;
  185. border === "surround" &&
  186. (classes = classes.concat(["u-border", "u-input--radius"]));
  187. classes.push(`u-input--${shape}`);
  188. border === "bottom" &&
  189. (classes = classes.concat([
  190. "u-border-bottom",
  191. "u-input--no-radius",
  192. ]));
  193. return classes.join(" ");
  194. },
  195. // 组件的样式
  196. wrapperStyle() {
  197. const style = {};
  198. // 禁用状态下,被背景色加上对应的样式
  199. if (this.disabled) {
  200. style.backgroundColor = this.disabledColor;
  201. }
  202. // 无边框时,去除内边距
  203. if (this.border === "none") {
  204. style.padding = "0";
  205. } else {
  206. // 由于uni-app的iOS开发者能力有限,导致需要分开写才有效
  207. style.paddingTop = "6px";
  208. style.paddingBottom = "6px";
  209. style.paddingLeft = "9px";
  210. style.paddingRight = "9px";
  211. }
  212. return deepMerge(style, addStyle(this.customStyle));
  213. },
  214. // 输入框的样式
  215. inputStyle() {
  216. const style = {
  217. color: this.color,
  218. fontSize: addUnit(this.fontSize),
  219. textAlign: this.inputAlign
  220. };
  221. return style;
  222. },
  223. },
  224. // #ifdef VUE3
  225. emits: ['update:modelValue', 'focus', 'blur', 'change', 'confirm', 'clear', 'keyboardheightchange'],
  226. // #endif
  227. methods: {
  228. // 在微信小程序中,不支持将函数当做props参数,故只能通过ref形式调用
  229. setFormatter(e) {
  230. this.innerFormatter = e
  231. },
  232. // 当键盘输入时,触发input事件
  233. onInput(e) {
  234. let { value = "" } = e.detail || {};
  235. // 为了避免props的单向数据流特性,需要先将innerValue值设置为当前值,再在$nextTick中重新赋予设置后的值才有效
  236. this.innerValue = value;
  237. this.$nextTick(() => {
  238. let formatValue = this.innerFormatter(value);
  239. this.innerValue = formatValue;
  240. this.valueChange(formatValue);
  241. })
  242. },
  243. // 输入框失去焦点时触发
  244. onBlur(event) {
  245. this.$emit("blur", event.detail.value);
  246. // H5端的blur会先于点击清除控件的点击click事件触发,导致focused
  247. // 瞬间为false,从而隐藏了清除控件而无法被点击到
  248. sleep(150).then(() => {
  249. this.focused = false;
  250. });
  251. // 尝试调用u-form的验证方法
  252. formValidate(this, "blur");
  253. },
  254. // 输入框聚焦时触发
  255. onFocus(event) {
  256. this.focused = true;
  257. this.$emit("focus");
  258. },
  259. // 点击完成按钮时触发
  260. onConfirm(event) {
  261. this.$emit("confirm", this.innerValue);
  262. },
  263. // 键盘高度发生变化的时候触发此事件
  264. // 兼容性:微信小程序2.7.0+、App 3.1.0+
  265. onkeyboardheightchange(event) {
  266. this.$emit("keyboardheightchange", event);
  267. },
  268. // 内容发生变化,进行处理
  269. valueChange(value, isOut = false) {
  270. if(this.clearInput) {
  271. this.innerValue = '';
  272. this.clearInput = false;
  273. }
  274. this.$nextTick(() => {
  275. if (!isOut || this.clearInput) {
  276. // 标识value值的变化是由内部引起的
  277. this.changeFromInner = true;
  278. this.$emit("change", value);
  279. // #ifdef VUE3
  280. this.$emit("update:modelValue", value);
  281. // #endif
  282. // #ifdef VUE2
  283. this.$emit("input", value);
  284. // #endif
  285. }
  286. // 尝试调用u-form的验证方法
  287. formValidate(this, "change");
  288. });
  289. },
  290. // 点击清除控件
  291. onClear() {
  292. this.clearInput = true;
  293. this.innerValue = "";
  294. this.$nextTick(() => {
  295. this.valueChange("");
  296. this.$emit("clear");
  297. });
  298. },
  299. /**
  300. * 在安卓nvue上事件无法冒泡
  301. * 在某些时间我们希望监听u-from-item的点击事件此时会导致点击u-form-item内的u-input后
  302. * 无法触发u-form-item的点击事件这里通过手动调用u-form-item的方法进行触发
  303. */
  304. clickHandler() {
  305. // #ifdef APP-NVUE
  306. if (os() === "android") {
  307. const formItem = $parent.call(this, "u-form-item");
  308. if (formItem) {
  309. formItem.clickHandler();
  310. }
  311. }
  312. // #endif
  313. },
  314. },
  315. };
  316. </script>
  317. <style lang="scss" scoped>
  318. @import "../../libs/css/components.scss";
  319. .u-input {
  320. @include flex(row);
  321. align-items: center;
  322. justify-content: space-between;
  323. flex: 1;
  324. &--radius,
  325. &--square {
  326. border-radius: 4px;
  327. }
  328. &--no-radius {
  329. border-radius: 0;
  330. }
  331. &--circle {
  332. border-radius: 100px;
  333. }
  334. &__content {
  335. flex: 1;
  336. @include flex(row);
  337. align-items: center;
  338. justify-content: space-between;
  339. &__field-wrapper {
  340. position: relative;
  341. @include flex(row);
  342. margin: 0;
  343. flex: 1;
  344. &__field {
  345. line-height: 26px;
  346. text-align: left;
  347. color: $u-main-color;
  348. height: 24px;
  349. font-size: 15px;
  350. flex: 1;
  351. }
  352. }
  353. &__clear {
  354. width: 20px;
  355. height: 20px;
  356. border-radius: 100px;
  357. background-color: #c6c7cb;
  358. @include flex(row);
  359. align-items: center;
  360. justify-content: center;
  361. transform: scale(0.82);
  362. margin-left: 4px;
  363. }
  364. &__subfix-icon {
  365. margin-left: 4px;
  366. }
  367. &__prefix-icon {
  368. margin-right: 4px;
  369. }
  370. }
  371. }
  372. </style>