index.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { VantComponent } from '../common/component';
  2. VantComponent({
  3. field: true,
  4. relation: {
  5. name: 'dropdown-menu',
  6. type: 'ancestor',
  7. linked(target) {
  8. this.parent = target;
  9. },
  10. unlinked() {
  11. this.parent = null;
  12. }
  13. },
  14. props: {
  15. value: null,
  16. title: String,
  17. disabled: Boolean,
  18. titleClass: String,
  19. options: {
  20. type: Array,
  21. value: []
  22. }
  23. },
  24. data: {
  25. transition: true,
  26. showPopup: false,
  27. showWrapper: false,
  28. displayTitle: ''
  29. },
  30. created() {
  31. this.setData({ displayTitle: this.computedDisplayTitle(this.data.value) });
  32. },
  33. methods: {
  34. computedDisplayTitle(curValue) {
  35. const { title, options } = this.data;
  36. if (title) {
  37. return title;
  38. }
  39. const match = options.filter(option => option.value === curValue);
  40. const displayTitle = match.length ? match[0].text : '';
  41. return displayTitle;
  42. },
  43. onClickOverlay() {
  44. this.toggle();
  45. this.$emit('close');
  46. },
  47. onOptionTap(event) {
  48. let { value, displayTitle } = this.data;
  49. const { option } = event.currentTarget.dataset;
  50. const { value: optionValue } = option;
  51. if (optionValue !== value) {
  52. value = optionValue;
  53. displayTitle = this.computedDisplayTitle(optionValue);
  54. this.$emit('change', optionValue);
  55. }
  56. this.setData({ showPopup: false, value, displayTitle });
  57. const time = this.data.duration || 0;
  58. setTimeout(() => {
  59. this.setData({ showWrapper: false });
  60. }, time);
  61. // parent 中的 itemListData 是 children 上的数据的集合
  62. // 数据的更新由 children 各自维护,但是模板的更新需要额外触发 parent 的 setData
  63. this.parent.setData({ itemListData: this.parent.data.itemListData });
  64. },
  65. toggle() {
  66. const { childIndex } = this.data;
  67. this.parent.toggleItem(childIndex);
  68. }
  69. }
  70. });