// components/tabs/tabs.js Component({ /** * 组件的属性列表 */ properties: { titles: { type: Array, value: [], }, index: { type: Number, value: 0, observer: function (newVal, oldVal) { // 属性值变化时执行 this.setData({ selectIndex: newVal, }); }, }, isCenter: { type: Boolean, value: false, }, }, /** * 组件的初始数据 */ data: { selectIndex: 0, scrollLeft: 0, //tab标题的滚动条位置 screenW: 0, }, // 生命周期函数,可以为函数,或一个在methods段中定义的方法名 attached: function () { const _this = this; wx.getSystemInfo({ success: function (res) { // 根据 model 进行判断 _this.data.screenW = res.screenWidth; }, }); }, /** * 组件的方法列表 */ methods: { tapAction: function (e) { const { currentIndex, currentItem } = e.currentTarget.dataset; this.setData({ selectIndex: currentIndex, }); this.triggerEvent("tab", { index: currentIndex, item: currentItem, }); if (!this.properties.isCenter) { const _x = e.currentTarget.offsetLeft; const _offsetLeft = _x - this.data.screenW / 2.0; if (this.data.selectIndex > 3 && _offsetLeft > 0) { this.setData({ scrollLeft: _offsetLeft, }); } else { this.setData({ scrollLeft: 0, }); } } }, }, });