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

类似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;
        }
        
    }
    
}
发布了248 篇原创文章 · 获赞 32 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/qq_37899792/article/details/105572379