组件使用(1-组件内部使用)

声明组件
{
  "usingComponents": {
      "Tabs": "../../components/Tabs/Tabs "
  }
}
 
使用组件
<Tabs></Tabs>
 
<!--components/Tabs/Tabs.wxml-->
<view class="tabs">
    <view class="tabs_title">
            <!-- <view class="title_item active">首页</view>
            <view class="title_item">原创</view>
            <view class="title_item">分类</view>
            <view class="title_item">关于</view>  -->


            <view 
                wx:for="{{tabs}}"
                wx:key="id"
                class="title_item {{item.isActive ? 'active' : ' '}}"
                bindtap="handleItemTap"
                data-index="{{index}}"
                >

                {{item.name}}
              
            </view>

    </view>

    <view class="tabs_content">内容</view>
</view>
 
/* components/Tabs/Tabs.wxss */

.tabs{ 
}

.tabs_title{
    display: flex;
    padding: 10rpx 0; 
}

.title_item{
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    padding-bottom: 20rpx;
}

.active{
    color: red; 
    border-bottom: 6rpx solid currentColor;
}
 
 
 
// components/Tabs/Tabs.js
Component({
    /**
     * 组件的属性列表
     */
    properties: {

    },

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

      /* 
  1 页面.js 文件中 存放事件回调函数的时候 存放在data同层级下!!!
  2 组件.js 文件中 存放事件回调函数的时候 必须要存在在 methods中!!!
   */
  
    /**
     * 组件的方法列表
     */
    methods: {
        handleItemTap(e){
         /* 
      1 绑定点击事件  需要在methods中绑定
      2 获取被点击的索引 
      3 获取原数组 
      4 对数组循环
        1 给每一个循环性 选中属性 改为 false
        2 给 当前的索引的 项 添加激活选中效果就可以了!!!

       
       5 点击事件触发的时候 
          触发父组件中的自定义事件 同时传递数据给  父组件  
          this.triggerEvent("父组件自定义事件的名称",要传递的参数)
       */

      //  2 获取索引
      const {index}=e.currentTarget.dataset;
      // 5 触发父组件中的自定义事件 同时传递数据给  
      this.triggerEvent("itemChange",{index});
      // 3 获取data中的数组
      // 解构  对 复杂类型进行结构的时候 复制了一份 变量的引用而已
      // 最严谨的做法 重新拷贝一份 数组,再对这个数组的备份进行处理,
      // let tabs=JSON.parse(JSON.stringify(this.data.tabs));
      // 不要直接修改 this.data.数据 
      // let {tabs}=this.data;
      // let tabs=this.data;
      // 4 循环数组
      // [].forEach 遍历数组 遍历数组的时候 修改了 v ,也会导致源数组被修改
      // tabs.forEach((v,i)=>i===index?v.isActive=true:v.isActive=false);

            this.setData({
                tabs
            })
        }
    }
})
 
 
 
 
posted @ 2021-01-18 12:04  13522679763-任国强  阅读(110)  评论(0)    收藏  举报