原创: 自定义tabs切换组件并使用(微信小程序中

1)TabsTop.wxml 此案例是在微信小程序中
<!-- components/Tabs/TabsTop.wxml -->
<text>components/Tabs/TabsTop.wxml</text>
<button type="primary">组件TabsTop</button>
<view class="header">
<!-- 导航 -->
<view class="tabs-group">
<!-- <view class="item active">首页</view>
<view class="item">原创</view>
<view class="item">产品</view>
<view class="item">关于</view> -->
<view wx:for="{{ tabs }}" wx:for-index="{{ index }}" wx:for-item="item" wx:key="id" class="item {{item.isActive?'active':''}}" bindtap="handleSelect"
data-index="{{item.id}}"
>
{{item.name}}
</view>
</view>
<view class="content">content</view>
<view></view>
</view>
2:tabsTop.js
// components/Tabs/TabsTop.js
Component ({
/**
* 组件的属性列表
*/
properties: {},
/**
* 组件的初始数据
*/
data: {
msg:'tabs分栏',
tabs: [
{
id: 0,
name: '首页',
isActive: true,
},
{
id: 1,
name: '原创',
isActive: false,
},
{
id: 2,
name: '商品',
isActive: false,
},
{
id: 3,
name: '关于',
isActive: false,
},
],
},
/**
* 组件的方法列表
*/
methods: {
handleSelect: function (e) {
console.log (e);
console.log (e.currentTarget.dataset.index);
let indexClick=e.currentTarget.dataset.index
/*
let {tabs}=this.data;
1:如上语句采用解构赋值,通过解构赋值, 可以将属性/值从对象/数组中取出,赋值给其他变量。
2:如上操作修改就不会更改this.data.tabs里的值。强调{tabs}是this.data的属性,非被复制对象的数据名称则不可以
*/
let {tabs}=this.data;
console.log(this.data)
console.log(tabs)
/*
通过解构赋值到新的变量名为tabs的数组(存放对象)中,循环拿出比较对象的为v
v.isActive是某个对象的属性isActive的值
*/
tabs.forEach((v,i)=>i===indexClick?v.isActive=true:v.isActive=false)
/*
setData函数主要用于将逻辑层数据发送到视图层,同时对应的改变this.data.x的值。
*/
var test03="test03的值哦"
this.setData({
tabs,
test03 //虽然this.data数据中没test03,
})
console.log(tabs)
console.log("-----------------解构赋值--------------------")
console.log(this.data.test03)
//解析赋值语法是一种javascript表达式。通过解构赋值,可以将属性/值从对象/数组中取出,赋值给其他变量。
},
},
});
3:tabsTop.wxss
.header{}
.tabs-group{
display: flex;
padding: 10rpx;
}
.item{
flex:auto;
justify-content: center;
display: flex;
}
.content{}
.active{
border-bottom: 10rpx solid red;
}
4:tabsTop.json
{
"component": true,
"usingComponents": {}
}
"component": true, 表示采用是组件
二:使用自定义组件
1:引入组件 如在componentUsed.json

2:使用自定义组件 componentUsed.wxml

做产品的程序,才是好的程序员!
浙公网安备 33010602011771号