猫妈狗爸伴宠师小程序前端代码
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.

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