微信小程序学习笔记——自定义组件步骤

类似vue或者react中的自定义组件

步骤:

Step1:新增组件

① 根目录下新建 components 文件夹

② 在 components 文件夹中,新建自定义组件文件夹

 

③ 右击  Tabs 文件夹 ,然后点击 弹出的菜单中的 “新建Compent”,输入组件名称,自动生成4个文件

 

Step2 :声明组件

Step3 :使用组件  

<view class="tabs">
    <view class="tabs_title">
        <!-- <view class="title_item active">首页</view>
        <view class="title_item">原创</view>
        <view class="title_item">关于</view> -->
        <view 
            wx:for="{{tabs}}" 
            wx:key="{{id}}" 
            data-index="{{index}}"
            class="title_item {{item.isActive?'active':''}}"
            bindtap="handleItemTap"
        >
            {{item.name}}
        </view>
          
    </view>
    <view class="tabs_content">
            <view class="detail">
                
            </view>
              
    </view>
</view>

// components/Tabs/Tabs.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    tabs:[
      {
        id:0,
        name:'首页',
        isActive:true
      },
      {
        id:1,
        name:'原创',
        isActive:false
      },
      {
        id:2,
        name:'分类',
        isActive:false
      },
      {
        id:3,
        name:'关于',
        isActive:false
      }
    ]
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleItemTap(e){
      const {index} = e.currentTarget.dataset

      //最严谨的写法 重新拷贝一份数组 ,在对这个额数组的备份进行处理
      //let list = JSON.parse(JSON.stringify(this.data.tabs))
      //不要直接修改 this.data.数据
      let list = this.data.tabs;
      list.forEach((v,i) => {
       // i===index ?v.isActive = true: v.isActive = false
        if(i==index){
          v.isActive = true
        }else{
          v.isActive = false
        }
      });
      console.log(list)
      this.setData({
        tabs:list
      })
    },
  }
})
/* components/Tabs/Tabs.less */
.tabs{
    display: flex;
    flex-direction: column;
    height: 100%;
    .tabs_title{
        display: flex;
        padding: 10rpx;
        .title_item{
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            padding:5rpx;
            border-bottom:  5rpx solid transparent;
        }
        .active{
            color: red;
            border-bottom:  5rpx solid currentColor;
        
        }
    }
    .tabs_content{
        flex:1;
       overflow: auto;
        .detail{
            height: 1000px;
        }
        
    }
    
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值