label-wrap.vue 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <script>
  2. export default {
  3. props: {
  4. isAutoWidth: Boolean,
  5. updateAll: Boolean
  6. },
  7. inject: ['elForm', 'elFormItem'],
  8. render() {
  9. const slots = this.$slots.default;
  10. if (!slots) return null;
  11. if (this.isAutoWidth) {
  12. const autoLabelWidth = this.elForm.autoLabelWidth;
  13. const style = {};
  14. if (autoLabelWidth && autoLabelWidth !== 'auto') {
  15. const marginLeft = parseInt(autoLabelWidth, 10) - this.computedWidth;
  16. if (marginLeft) {
  17. style.marginLeft = marginLeft + 'px';
  18. }
  19. }
  20. return (<div class="el-form-item__label-wrap" style={style}>
  21. { slots }
  22. </div>);
  23. } else {
  24. return slots[0];
  25. }
  26. },
  27. methods: {
  28. getLabelWidth() {
  29. if (this.$el && this.$el.firstElementChild) {
  30. const computedWidth = window.getComputedStyle(this.$el.firstElementChild).width;
  31. return Math.ceil(parseFloat(computedWidth));
  32. } else {
  33. return 0;
  34. }
  35. },
  36. updateLabelWidth(action = 'update') {
  37. if (this.$slots.default && this.isAutoWidth && this.$el.firstElementChild) {
  38. if (action === 'update') {
  39. this.computedWidth = this.getLabelWidth();
  40. } else if (action === 'remove') {
  41. this.elForm.deregisterLabelWidth(this.computedWidth);
  42. }
  43. }
  44. }
  45. },
  46. watch: {
  47. computedWidth(val, oldVal) {
  48. if (this.updateAll) {
  49. this.elForm.registerLabelWidth(val, oldVal);
  50. this.elFormItem.updateComputedLabelWidth(val);
  51. }
  52. }
  53. },
  54. data() {
  55. return {
  56. computedWidth: 0
  57. };
  58. },
  59. mounted() {
  60. this.updateLabelWidth('update');
  61. },
  62. updated() {
  63. this.updateLabelWidth('update');
  64. },
  65. beforeDestroy() {
  66. this.updateLabelWidth('remove');
  67. }
  68. };
  69. </script>