u-input.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 {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时光标的位置( 默认 140 )
  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. // console.log('onInput', value, this.innerValue)
  237. this.innerValue = value;
  238. this.$nextTick(() => {
  239. let formatValue = this.innerFormatter(value);
  240. this.innerValue = formatValue;
  241. this.valueChange(formatValue);
  242. })
  243. },
  244. // 输入框失去焦点时触发
  245. onBlur(event) {
  246. this.$emit("blur", event.detail.value);
  247. // H5端的blur会先于点击清除控件的点击click事件触发,导致focused
  248. // 瞬间为false,从而隐藏了清除控件而无法被点击到
  249. sleep(150).then(() => {
  250. this.focused = false;
  251. });
  252. // 尝试调用u-form的验证方法
  253. formValidate(this, "blur");
  254. },
  255. // 输入框聚焦时触发
  256. onFocus(event) {
  257. this.focused = true;
  258. this.$emit("focus");
  259. },
  260. // 点击完成按钮时触发
  261. onConfirm(event) {
  262. this.$emit("confirm", this.innerValue);
  263. },
  264. // 键盘高度发生变化的时候触发此事件
  265. // 兼容性:微信小程序2.7.0+、App 3.1.0+
  266. onkeyboardheightchange(event) {
  267. this.$emit("keyboardheightchange", event);
  268. },
  269. // 内容发生变化,进行处理
  270. valueChange(value, isOut = false) {
  271. if(this.clearInput) {
  272. this.innerValue = '';
  273. this.clearInput = false;
  274. }
  275. this.$nextTick(() => {
  276. if (!isOut || this.clearInput) {
  277. // 标识value值的变化是由内部引起的
  278. this.changeFromInner = true;
  279. this.$emit("change", value);
  280. // #ifdef VUE3
  281. this.$emit("update:modelValue", value);
  282. // #endif
  283. // #ifdef VUE2
  284. this.$emit("input", value);
  285. // #endif
  286. }
  287. // 尝试调用u-form的验证方法
  288. formValidate(this, "change");
  289. });
  290. },
  291. // 点击清除控件
  292. onClear() {
  293. this.clearInput = true;
  294. this.innerValue = "";
  295. this.$nextTick(() => {
  296. this.valueChange("");
  297. this.$emit("clear");
  298. });
  299. },
  300. /**
  301. * 在安卓nvue上,事件无法冒泡
  302. * 在某些时间,我们希望监听u-from-item的点击事件,此时会导致点击u-form-item内的u-input后
  303. * 无法触发u-form-item的点击事件,这里通过手动调用u-form-item的方法进行触发
  304. */
  305. clickHandler() {
  306. // #ifdef APP-NVUE
  307. if (os() === "android") {
  308. const formItem = $parent.call(this, "u-form-item");
  309. if (formItem) {
  310. formItem.clickHandler();
  311. }
  312. }
  313. // #endif
  314. },
  315. },
  316. };
  317. </script>
  318. <style lang="scss" scoped>
  319. @import "../../libs/css/components.scss";
  320. .u-input {
  321. @include flex(row);
  322. align-items: center;
  323. justify-content: space-between;
  324. flex: 1;
  325. &--radius,
  326. &--square {
  327. border-radius: 4px;
  328. }
  329. &--no-radius {
  330. border-radius: 0;
  331. }
  332. &--circle {
  333. border-radius: 100px;
  334. }
  335. &__content {
  336. flex: 1;
  337. @include flex(row);
  338. align-items: center;
  339. justify-content: space-between;
  340. &__field-wrapper {
  341. position: relative;
  342. @include flex(row);
  343. margin: 0;
  344. flex: 1;
  345. &__field {
  346. line-height: 26px;
  347. text-align: left;
  348. color: $u-main-color;
  349. height: 24px;
  350. font-size: 15px;
  351. flex: 1;
  352. }
  353. }
  354. &__clear {
  355. width: 20px;
  356. height: 20px;
  357. border-radius: 100px;
  358. background-color: #c6c7cb;
  359. @include flex(row);
  360. align-items: center;
  361. justify-content: center;
  362. transform: scale(0.82);
  363. margin-left: 4px;
  364. }
  365. &__subfix-icon {
  366. margin-left: 4px;
  367. }
  368. &__prefix-icon {
  369. margin-right: 4px;
  370. }
  371. }
  372. }
  373. </style>