u-input.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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="placeholderStyle"
  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. // 过滤处理方法
  153. innerFormatter: value => value,
  154. showPassword: false
  155. };
  156. },
  157. created() {
  158. // 格式化过滤方法
  159. if (this.formatter) {
  160. this.innerFormatter = this.formatter;
  161. }
  162. },
  163. watch: {
  164. modelValue: {
  165. immediate: true,
  166. handler(newVal, oldVal) {
  167. // console.log(newVal, oldVal)
  168. if (this.changeFromInner || this.innerValue === newVal) {
  169. this.changeFromInner = false; // 重要否则会出现双向绑定失效问题https://github.com/ijry/uview-plus/issues/419
  170. return;
  171. }
  172. this.innerValue = newVal;
  173. // 在H5中,外部value变化后,修改input中的值,不会触发@input事件,此时手动调用值变化方法
  174. if (
  175. this.firstChange === false &&
  176. this.changeFromInner === false
  177. ) {
  178. this.valueChange(this.innerValue, true);
  179. } else {
  180. // 尝试调用up-form的验证方法
  181. if(!this.firstChange) formValidate(this, "change");
  182. }
  183. this.firstChange = false;
  184. // 重置changeFromInner的值为false,标识下一次引起默认为外部引起的
  185. this.changeFromInner = false;
  186. }
  187. }
  188. },
  189. computed: {
  190. // 是否密码
  191. isPassword() {
  192. let ret = false;
  193. if(this.password) {
  194. ret = true;
  195. } else if (this.type == 'password') {
  196. ret = true;
  197. } else {
  198. ret = false;
  199. }
  200. if (this.showPassword) {
  201. ret = false;
  202. }
  203. return ret;
  204. },
  205. // 是否显示清除控件
  206. isShowClear() {
  207. const { clearable, readonly, focused, innerValue, onlyClearableOnFocused } = this;
  208. if (!clearable || readonly) {
  209. return false;
  210. }
  211. if (onlyClearableOnFocused) {
  212. return !!focused && innerValue !== "";
  213. } else {
  214. return innerValue !== "";
  215. }
  216. },
  217. // 组件的类名
  218. inputClass() {
  219. let classes = [],
  220. { border, disabled, shape } = this;
  221. border === "surround" &&
  222. (classes = classes.concat(["u-border", "u-input--radius"]));
  223. classes.push(`u-input--${shape}`);
  224. border === "bottom" &&
  225. (classes = classes.concat([
  226. "u-border-bottom",
  227. "u-input--no-radius",
  228. ]));
  229. return classes.join(" ");
  230. },
  231. // 组件的样式
  232. wrapperStyle() {
  233. const style = {};
  234. // 禁用状态下,被背景色加上对应的样式
  235. if (this.disabled) {
  236. style.backgroundColor = this.disabledColor;
  237. }
  238. // 无边框时,去除内边距
  239. if (this.border === "none") {
  240. style.padding = "0";
  241. } else {
  242. // 由于uni-app的iOS端限制,导致需要分开写才有效
  243. style.paddingTop = "6px";
  244. style.paddingBottom = "6px";
  245. style.paddingLeft = "9px";
  246. style.paddingRight = "9px";
  247. }
  248. return deepMerge(style, addStyle(this.customStyle));
  249. },
  250. // 输入框的样式
  251. inputStyle() {
  252. const style = {
  253. color: this.color,
  254. fontSize: addUnit(this.fontSize),
  255. textAlign: this.inputAlign
  256. };
  257. return style;
  258. },
  259. },
  260. // #ifdef VUE3
  261. emits: ['update:modelValue', 'focus', 'blur', 'change', 'confirm', 'clear', 'keyboardheightchange', 'nicknamereview'],
  262. // #endif
  263. methods: {
  264. // 在微信小程序中,不支持将函数当做props参数,故只能通过ref形式调用
  265. setFormatter(e) {
  266. this.innerFormatter = e
  267. },
  268. // 当键盘输入时,触发input事件
  269. onInput(e) {
  270. let { value = "" } = e.detail || {};
  271. // 为了避免props的单向数据流特性,需要先将innerValue值设置为当前值,再在$nextTick中重新赋予设置后的值才有效
  272. // console.log('onInput', value, this.innerValue)
  273. this.innerValue = value;
  274. this.$nextTick(() => {
  275. let formatValue = this.innerFormatter(value);
  276. this.innerValue = formatValue;
  277. this.valueChange(formatValue);
  278. })
  279. },
  280. // 输入框失去焦点时触发
  281. onBlur(event) {
  282. this.$emit("blur", event.detail.value);
  283. // H5端的blur会先于点击清除控件的点击click事件触发,导致focused
  284. // 瞬间为false,从而隐藏了清除控件而无法被点击到
  285. sleep(150).then(() => {
  286. this.focused = false;
  287. });
  288. // 尝试调用u-form的验证方法
  289. formValidate(this, "blur");
  290. },
  291. // 输入框聚焦时触发
  292. onFocus(event) {
  293. this.focused = true;
  294. this.$emit("focus");
  295. },
  296. doFocus() {
  297. this.$refs['input-native'].focus();
  298. },
  299. doBlur() {
  300. this.$refs['input-native'].blur();
  301. },
  302. // 点击完成按钮时触发
  303. onConfirm(event) {
  304. this.$emit("confirm", this.innerValue);
  305. },
  306. // 键盘高度发生变化的时候触发此事件
  307. // 兼容性:微信小程序2.7.0+、App 3.1.0+
  308. onkeyboardheightchange(event) {
  309. this.$emit("keyboardheightchange", event);
  310. },
  311. onnicknamereview(event) {
  312. this.$emit("nicknamereview", event);
  313. },
  314. // 内容发生变化,进行处理
  315. valueChange(value, isOut = false) {
  316. if(this.clearInput) {
  317. this.innerValue = '';
  318. this.clearInput = false;
  319. }
  320. this.$nextTick(() => {
  321. if (!isOut || this.clearInput) {
  322. // 标识value值的变化是由内部引起的
  323. this.changeFromInner = true;
  324. this.$emit("change", value);
  325. // #ifdef VUE3
  326. this.$emit("update:modelValue", value);
  327. // #endif
  328. // #ifdef VUE2
  329. this.$emit("input", value);
  330. // #endif
  331. }
  332. // 尝试调用u-form的验证方法
  333. formValidate(this, "change");
  334. });
  335. },
  336. // 点击清除控件
  337. onClear() {
  338. this.clearInput = true;
  339. this.innerValue = "";
  340. this.$nextTick(() => {
  341. this.valueChange("");
  342. this.$emit("clear");
  343. });
  344. },
  345. /**
  346. * 在安卓nvue上,事件无法冒泡
  347. * 在某些时间,我们希望监听u-from-item的点击事件,此时会导致点击u-form-item内的u-input后
  348. * 无法触发u-form-item的点击事件,这里通过手动调用u-form-item的方法进行触发
  349. */
  350. clickHandler() {
  351. if (this.disabled || this.readonly) {
  352. uni.hideKeyboard();
  353. }
  354. // #ifdef APP-NVUE
  355. if (os() === "android") {
  356. const formItem = $parent.call(this, "u-form-item");
  357. if (formItem) {
  358. formItem.clickHandler();
  359. }
  360. }
  361. // #endif
  362. },
  363. },
  364. };
  365. </script>
  366. <style lang="scss" scoped>
  367. .u-input {
  368. @include flex(row);
  369. align-items: center;
  370. justify-content: space-between;
  371. flex: 1;
  372. &--radius,
  373. &--square {
  374. border-radius: 4px;
  375. }
  376. &--no-radius {
  377. border-radius: 0;
  378. }
  379. &--circle {
  380. border-radius: 100px;
  381. }
  382. &__content {
  383. flex: 1;
  384. @include flex(row);
  385. align-items: center;
  386. justify-content: space-between;
  387. &__field-wrapper {
  388. position: relative;
  389. @include flex(row);
  390. margin: 0;
  391. flex: 1;
  392. &__field {
  393. line-height: 26px;
  394. text-align: left;
  395. color: $u-main-color;
  396. height: 24px;
  397. font-size: 15px;
  398. flex: 1;
  399. }
  400. }
  401. &__clear {
  402. width: 20px;
  403. height: 20px;
  404. border-radius: 100px;
  405. background-color: #c6c7cb;
  406. @include flex(row);
  407. align-items: center;
  408. justify-content: center;
  409. transform: scale(0.82);
  410. margin-left: 4px;
  411. }
  412. &__subfix-icon {
  413. margin-left: 4px;
  414. }
  415. &__prefix-icon {
  416. margin-right: 4px;
  417. }
  418. }
  419. }
  420. </style>