demo5.vue 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <template>
  2. <m-tree
  3. ref="treeRef"
  4. :data="list"
  5. node-key="id"
  6. show-checkbox
  7. default-expand-all
  8. style="margin-bottom:20px">
  9. </m-tree>
  10. <m-space>
  11. <m-button type="primary" @click="setCheckedKeys">通过node-key设置选中</m-button>
  12. <m-button type="primary" @click="getCheckedNodes">获取选中项的数据数组</m-button>
  13. <m-button type="primary" @click="getCheckedKeys">获取选中项的keys数组</m-button>
  14. <m-button type="primary" @click="resetChecked">清空选中项</m-button>
  15. </m-space>
  16. </template>
  17. <script setup>
  18. import { ref } from 'vue-demi';
  19. const treeRef = ref(null);
  20. const list = [
  21. {
  22. id: 1,
  23. label: '一级 1',
  24. children: [
  25. {
  26. id: 4,
  27. label: '二级 1-1',
  28. children: [
  29. {
  30. id: 10,
  31. label: '三级 1-1-1'
  32. },
  33. {
  34. id: 11,
  35. label: '三级 1-1-2'
  36. }
  37. ]
  38. },
  39. {
  40. id: 5,
  41. label: '二级 1-2'
  42. }
  43. ]
  44. },
  45. {
  46. id: 2,
  47. label: '一级 2',
  48. children: [
  49. {
  50. id: 6,
  51. label: '二级 2-1',
  52. children: [
  53. {
  54. id: 12,
  55. label: '三级 2-1-1'
  56. }
  57. ]
  58. },
  59. {
  60. id: 7,
  61. label: '二级 2-2'
  62. }
  63. ]
  64. },
  65. {
  66. id: 3,
  67. label: '一级 3',
  68. children: [
  69. {
  70. id: 8,
  71. label: '二级 3-1'
  72. },
  73. {
  74. id: 9,
  75. label: '二级 3-2'
  76. }
  77. ]
  78. }
  79. ]
  80. const setCheckedKeys = () => {
  81. treeRef.value.setCheckedKeys([4])
  82. }
  83. const getCheckedNodes = () => {
  84. const nodes = treeRef.value.getCheckedNodes()
  85. alert(JSON.stringify(nodes))
  86. console.log(nodes);
  87. }
  88. const getCheckedKeys = () => {
  89. const keys = treeRef.value.getCheckedKeys()
  90. alert(JSON.stringify(keys))
  91. console.log(keys);
  92. }
  93. const resetChecked = () => {
  94. treeRef.value.setCheckedKeys([])
  95. }
  96. </script>