tabs.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // components/tabs/tabs.js
  2. Component({
  3. /**
  4. * 组件的属性列表
  5. */
  6. properties: {
  7. titles: {
  8. type: Array,
  9. value: [],
  10. },
  11. index: {
  12. type: Number,
  13. value: 0,
  14. observer: function (newVal, oldVal) {
  15. // 属性值变化时执行
  16. this.setData({
  17. selectIndex: newVal,
  18. });
  19. },
  20. },
  21. isCenter: {
  22. type: Boolean,
  23. value: false,
  24. },
  25. },
  26. /**
  27. * 组件的初始数据
  28. */
  29. data: {
  30. selectIndex: 0,
  31. scrollLeft: 0, //tab标题的滚动条位置
  32. screenW: 0,
  33. },
  34. // 生命周期函数,可以为函数,或一个在methods段中定义的方法名
  35. attached: function () {
  36. const _this = this;
  37. wx.getSystemInfo({
  38. success: function (res) {
  39. // 根据 model 进行判断
  40. _this.data.screenW = res.screenWidth;
  41. },
  42. });
  43. },
  44. /**
  45. * 组件的方法列表
  46. */
  47. methods: {
  48. tapAction: function (e) {
  49. const { currentIndex, currentItem } = e.currentTarget.dataset;
  50. this.setData({
  51. selectIndex: currentIndex,
  52. });
  53. this.triggerEvent("tab", {
  54. index: currentIndex,
  55. item: currentItem,
  56. });
  57. if (!this.properties.isCenter) {
  58. const _x = e.currentTarget.offsetLeft;
  59. const _offsetLeft = _x - this.data.screenW / 2.0;
  60. if (this.data.selectIndex > 3 && _offsetLeft > 0) {
  61. this.setData({
  62. scrollLeft: _offsetLeft,
  63. });
  64. } else {
  65. this.setData({
  66. scrollLeft: 0,
  67. });
  68. }
  69. }
  70. },
  71. },
  72. });