3
0

u-input.vue 16 KB

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