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.
 
 
 

470 lines
19 KiB

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