a3e2dfbfff322b87cc8d30aaa8aff8a9127123677123c24d59ad8269f13cbaaf2405b1438f5129819f72ef9733a0319d0c8fdd252d05900ba96a2b2c8f3118 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { arrayFind } from 'element-ui/src/utils/util';
  2. import { getRowIdentity } from '../util';
  3. export default {
  4. data() {
  5. return {
  6. states: {
  7. // 不可响应的,设置 currentRowKey 时,data 不一定存在,也许无法算出正确的 currentRow
  8. // 把该值缓存一下,当用户点击修改 currentRow 时,把该值重置为 null
  9. _currentRowKey: null,
  10. currentRow: null
  11. }
  12. };
  13. },
  14. methods: {
  15. setCurrentRowKey(key) {
  16. this.assertRowKey();
  17. this.states._currentRowKey = key;
  18. this.setCurrentRowByKey(key);
  19. },
  20. restoreCurrentRowKey() {
  21. this.states._currentRowKey = null;
  22. },
  23. setCurrentRowByKey(key) {
  24. const { states } = this;
  25. const { data = [], rowKey } = states;
  26. let currentRow = null;
  27. if (rowKey) {
  28. currentRow = arrayFind(data, item => getRowIdentity(item, rowKey) === key);
  29. }
  30. states.currentRow = currentRow;
  31. },
  32. updateCurrentRow(currentRow) {
  33. const { states, table } = this;
  34. const oldCurrentRow = states.currentRow;
  35. if (currentRow && currentRow !== oldCurrentRow) {
  36. states.currentRow = currentRow;
  37. table.$emit('current-change', currentRow, oldCurrentRow);
  38. return;
  39. }
  40. if (!currentRow && oldCurrentRow) {
  41. states.currentRow = null;
  42. table.$emit('current-change', null, oldCurrentRow);
  43. }
  44. },
  45. updateCurrentRowData() {
  46. const { states, table } = this;
  47. const { rowKey, _currentRowKey } = states;
  48. // data 为 null 时,解构时的默认值会被忽略
  49. const data = states.data || [];
  50. const oldCurrentRow = states.currentRow;
  51. // 当 currentRow 不在 data 中时尝试更新数据
  52. if (data.indexOf(oldCurrentRow) === -1 && oldCurrentRow) {
  53. if (rowKey) {
  54. const currentRowKey = getRowIdentity(oldCurrentRow, rowKey);
  55. this.setCurrentRowByKey(currentRowKey);
  56. } else {
  57. states.currentRow = null;
  58. }
  59. if (states.currentRow === null) {
  60. table.$emit('current-change', null, oldCurrentRow);
  61. }
  62. } else if (_currentRowKey) {
  63. // 把初始时下设置的 rowKey 转化成 rowData
  64. this.setCurrentRowByKey(_currentRowKey);
  65. this.restoreCurrentRowKey();
  66. }
  67. }
  68. }
  69. };