index.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // 组件不支持简单的双向绑定,需要使用input和confirm事件来实现。
  2. Component({
  3. options: {
  4. multipleSlots: true,
  5. styleIsolation: "shared",
  6. },
  7. properties: {
  8. value: {
  9. type: Array,
  10. value: [],
  11. observer: "_value",
  12. },
  13. options: {
  14. required: true,
  15. type: Array,
  16. value: [],
  17. observer: "_options",
  18. },
  19. /** 排列方向,可选值为 vertical horizontal */
  20. direction: {
  21. type: String,
  22. value: "horizontal",
  23. },
  24. },
  25. data: {
  26. innerOptions: [] as any[],
  27. innerValue: [] as any[],
  28. },
  29. methods: {
  30. onCheckChange(event: any) {
  31. const value = event.detail;
  32. this.setData({
  33. value: value.map((v: any) => String(v)), // 只更新 innerValue
  34. });
  35. this.triggerEvent("change", value); // 将值传递给父组件
  36. },
  37. onChecked(val: any) {
  38. return this.data.innerValue.includes(val) ? true : false;
  39. },
  40. _value(newVal: any[]) {
  41. const tempVal: any[] = [];
  42. this.data.innerOptions.forEach((item: any) => {
  43. tempVal.push({
  44. ...item,
  45. isSelect: newVal.includes(item.value) ? true : false,
  46. });
  47. });
  48. this.setData({
  49. innerOptions: tempVal,
  50. innerValue: newVal.map((v: any) => String(v)), // 确保数据类型一致
  51. });
  52. },
  53. _options(newVal: any[]) {
  54. const value: any = this.data.value;
  55. const tempVal: any[] = [];
  56. newVal.forEach((item: any) => {
  57. tempVal.push({
  58. ...item,
  59. isSelect: value.includes(item.value) ? true : false,
  60. });
  61. });
  62. this.setData({
  63. innerOptions: tempVal,
  64. });
  65. },
  66. },
  67. });