经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
element-ui inputNumber组件源码分析整理笔记(三)
来源:cnblogs  作者:kristy1993  时间:2018/11/30 9:32:43  对本文有异议

inputNumber算是一个比较简单的组件了。

  1. <template>
  2. <!--@dragstart.prevent禁止input中数字的拖动-->
  3. <div
  4. @dragstart.prevent
  5. :class="[
  6. 'el-input-number',
  7. inputNumberSize ? 'el-input-number--' + inputNumberSize : '',
  8. { 'is-disabled': inputNumberDisabled },
  9. { 'is-without-controls': !controls },
  10. { 'is-controls-right': controlsAtRight }
  11. ]">
  12. <span
  13. class="el-input-number__decrease"
  14. role="button"
  15. v-if="controls"
  16. v-repeat-click="decrease"
  17. :class="{'is-disabled': minDisabled}"
  18. @keydown.enter="decrease">
  19. <i :class="`el-icon-${controlsAtRight ? 'arrow-down' : 'minus'}`"></i>
  20. </span>
  21. <span
  22. class="el-input-number__increase"
  23. role="button"
  24. v-if="controls"
  25. v-repeat-click="increase"
  26. :class="{'is-disabled': maxDisabled}"
  27. @keydown.enter="increase">
  28. <i :class="`el-icon-${controlsAtRight ? 'arrow-up' : 'plus'}`"></i>
  29. </span>
  30. <el-input
  31. ref="input"
  32. :value="currentInputValue"
  33. :placeholder="placeholder"
  34. :disabled="inputNumberDisabled"
  35. :size="inputNumberSize"
  36. :max="max"
  37. :min="min"
  38. :name="name"
  39. :label="label"
  40. @keydown.up.native.prevent="increase"
  41. @keydown.down.native.prevent="decrease"
  42. @blur="handleBlur"
  43. @focus="handleFocus"
  44. @change="handleInputChange">
  45. </el-input>
  46. </div>
  47. </template>
  48. <script>
  49. import ElInput from 'element-ui/packages/input';
  50. import Focus from 'element-ui/src/mixins/focus';
  51. //RepeatClick,用来控制左键按下时不断触发事件
  52. import RepeatClick from 'element-ui/src/directives/repeat-click';
  53. export default {
  54. name: 'ElInputNumber',
  55. mixins: [Focus('input')],
  56. inject: {
  57. elForm: {
  58. default: ''
  59. },
  60. elFormItem: {
  61. default: ''
  62. }
  63. },
  64. directives: {
  65. repeatClick: RepeatClick
  66. },
  67. components: {
  68. ElInput
  69. },
  70. props: {
  71. step: { //计数器步长
  72. type: Number,
  73. default: 1
  74. },
  75. max: { //设置计数器允许的最大值
  76. type: Number,
  77. default: Infinity
  78. },
  79. min: { //设置计数器允许的最小值
  80. type: Number,
  81. default: -Infinity
  82. },
  83. value: {}, //绑定值
  84. disabled: Boolean, //是否禁用计数器
  85. size: String, //计数器尺寸
  86. controls: { //是否使用控制按钮
  87. type: Boolean,
  88. default: true
  89. },
  90. controlsPosition: { //控制按钮位置
  91. type: String,
  92. default: ''
  93. },
  94. name: String, //原生属性
  95. label: String, //输入框关联的label文字
  96. placeholder: String, //输入框默认 placeholder
  97. precision: { //数值精度
  98. type: Number,
  99. validator(val) {
  100. return val >= 0 && val === parseInt(val, 10);
  101. }
  102. }
  103. },
  104. data() {
  105. return {
  106. currentValue: 0
  107. };
  108. },
  109. watch: {
  110. value: {
  111. //确认是否以当前的初始值执行handler的函数。
  112. immediate: true,
  113. handler(value) {
  114. //Number() 函数把对象的值转换为数字。
  115. let newVal = value === undefined ? value : Number(value);
  116. if (newVal !== undefined) {
  117. if (isNaN(newVal)) {
  118. return;
  119. }
  120. if (this.precision !== undefined) {
  121. //如果数值精度存在,将数字按精度转换
  122. newVal = this.toPrecision(newVal, this.precision);
  123. }
  124. }
  125. if (newVal >= this.max) newVal = this.max;
  126. if (newVal <= this.min) newVal = this.min;
  127. this.currentValue = newVal;
  128. this.$emit('input', newVal);
  129. }
  130. }
  131. },
  132. computed: {
  133. // 返回当前减号是否被禁用
  134. minDisabled() {
  135. // 当前值-计数器步长<最小值时,减号被禁用,不能再继续减
  136. return this._decrease(this.value, this.step) < this.min;
  137. },
  138. maxDisabled() {
  139. return this._increase(this.value, this.step) > this.max;
  140. },
  141. //返回数值的精度
  142. numPrecision() {
  143. // precision 的值必须是一个非负整数,并且不能小于 step 的小数位数。
  144. const { value, step, getPrecision, precision } = this;
  145. const stepPrecision = getPrecision(step);
  146. if (precision !== undefined) {
  147. //如果step 的小数位数大于数值精度时,控制台输出警告并返回数值精度
  148. if (stepPrecision > precision) {
  149. console.warn('[Element Warn][InputNumber]precision should not be less than the decimal places of step');
  150. }
  151. return precision;
  152. } else {
  153. //如果step 的小数位数小于数值精度时,再比较数值的精度和step的精度,取最大值
  154. return Math.max(getPrecision(value), stepPrecision);
  155. }
  156. },
  157. // 控制按钮的位置
  158. controlsAtRight() {
  159. // 当控制按钮存在,并且控制按钮的位置为right时,此处通过添加is-controls-right类来改变控制按钮的位置,使控制按钮在右边显示。
  160. return this.controls && this.controlsPosition === 'right';
  161. },
  162. _elFormItemSize() {
  163. return (this.elFormItem || {}).elFormItemSize;
  164. },
  165. //计数器的大小
  166. inputNumberSize() {
  167. return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
  168. },
  169. // 是否禁用计数器
  170. inputNumberDisabled() {
  171. return this.disabled || (this.elForm || {}).disabled;
  172. },
  173. currentInputValue() {
  174. const currentValue = this.currentValue;
  175. if (typeof currentValue === 'number' && this.precision !== undefined) {
  176. return currentValue.toFixed(this.precision);
  177. } else {
  178. return currentValue;
  179. }
  180. }
  181. },
  182. methods: {
  183. //按精度转换数值
  184. toPrecision(num, precision) {
  185. if (precision === undefined) precision = this.numPrecision;
  186. //toFixed() 方法可把 Number 四舍五入为指定小数位数的数字,返回字符串;parseFloat()函数可解析一个字符串,并返回一个浮点数。
  187. return parseFloat(parseFloat(Number(num).toFixed(precision)));
  188. },
  189. //获取value的小数位数
  190. getPrecision(value) {
  191. if (value === undefined) return 0;
  192. const valueString = value.toString();
  193. const dotPosition = valueString.indexOf('.');
  194. let precision = 0;
  195. if (dotPosition !== -1) {
  196. //valueString.length减去小数点前面的位数,剩下的就是小数点后面的位数
  197. precision = valueString.length - dotPosition - 1;
  198. }
  199. return precision;
  200. },
  201. _increase(val, step) {
  202. if (typeof val !== 'number' && val !== undefined) return this.currentValue;
  203. const precisionFactor = Math.pow(10, this.numPrecision);
  204. return this.toPrecision((precisionFactor * val + precisionFactor * step) / precisionFactor);
  205. },
  206. //返回value减去step后的值
  207. _decrease(val, step) {
  208. if (typeof val !== 'number' && val !== undefined) return this.currentValue;
  209. //Math.pow()计算10的this.numPrecision次方
  210. const precisionFactor = Math.pow(10, this.numPrecision);
  211. //这里主要是为了减少误差
  212. return this.toPrecision((precisionFactor * val - precisionFactor * step) / precisionFactor);
  213. },
  214. increase() {
  215. if (this.inputNumberDisabled || this.maxDisabled) return;
  216. const value = this.value || 0;
  217. const newVal = this._increase(value, this.step);
  218. this.setCurrentValue(newVal);
  219. },
  220. //点击减号时触发的事件
  221. decrease() {
  222. if (this.inputNumberDisabled || this.minDisabled) return;
  223. const value = this.value || 0;
  224. const newVal = this._decrease(value, this.step);
  225. this.setCurrentValue(newVal);
  226. },
  227. handleBlur(event) {
  228. this.$emit('blur', event);
  229. this.$refs.input.setCurrentValue(this.currentInputValue);
  230. },
  231. handleFocus(event) {
  232. this.$emit('focus', event);
  233. },
  234. setCurrentValue(newVal) {
  235. const oldVal = this.currentValue;
  236. if (typeof newVal === 'number' && this.precision !== undefined) {
  237. newVal = this.toPrecision(newVal, this.precision);
  238. }
  239. if (newVal >= this.max) newVal = this.max;
  240. if (newVal <= this.min) newVal = this.min;
  241. if (oldVal === newVal) {
  242. //改变input的当前值
  243. this.$refs.input.setCurrentValue(this.currentInputValue);
  244. return;
  245. }
  246. this.$emit('input', newVal);
  247. this.$emit('change', newVal, oldVal);
  248. this.currentValue = newVal;
  249. },
  250. handleInputChange(value) {
  251. const newVal = value === '' ? undefined : Number(value);
  252. if (!isNaN(newVal) || value === '') {
  253. this.setCurrentValue(newVal);
  254. }
  255. },
  256. select() {
  257. this.$refs.input.select();
  258. }
  259. },
  260. mounted() {
  261. let innerInput = this.$refs.input.$refs.input;
  262. innerInput.setAttribute('role', 'spinbutton');
  263. innerInput.setAttribute('aria-valuemax', this.max);
  264. innerInput.setAttribute('aria-valuemin', this.min);
  265. innerInput.setAttribute('aria-valuenow', this.currentValue);
  266. innerInput.setAttribute('aria-disabled', this.inputNumberDisabled);
  267. },
  268. updated() {
  269. if (!this.$refs || !this.$refs.input) return;
  270. const innerInput = this.$refs.input.$refs.input;
  271. innerInput.setAttribute('aria-valuenow', this.currentValue);
  272. }
  273. };
  274. </script>

解析:
(1)先看下html结构

  1. <div class="el-input-number">
  2. <!--左边的减号-->
  3. <span class="el-input-number__decrease">
  4. <i class="el-icon-minus"></i>
  5. </span>
  6. <!--右边的加号-->
  7. <span class="el-input-number__increase">
  8. <i class="el-icon-plus"></i>
  9. </span>
  10. <!--中间的输入框-->
  11. <el-input ref="input"></el-input>
  12. </div>


左边的减号和右边的加号是通过绝对定位,设置在input左右的padding位置的,input的css代码如下:

  1. .el-input-number .el-input__inner {
  2. -webkit-appearance: none;
  3. padding-left: 50px;
  4. padding-right: 50px;
  5. text-align: center;
  6. }

这个inputNumber源码还算简单,多看几遍就懂了

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号