父向子传递,子向父传递

组件之Tabs.js文件

// components/Tabs/Tabs.js
Component({
  /**
   * 组件的属性列表
   */
  // 接受传递的数据
  properties: {
    tabs:{
      type:Array,
      value:[]
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    
  },
  /**
   * 组件的方法列表
   */
  methods: {
    hendleTabs(e){
      // console.log(e.currentTarget.dataset.index) //打印对象
      const index = e.currentTarget.dataset.index;
      //let tabs = this.data.tabs;//浅拷贝
      //let tabs = JSON .parse(JSON.stringify(this.data.tabs))  //深拷贝,建议使用
      //循环列表 改变isActive值
      //tabs.forEach((v,i)=> i===index?v.isActive=true:v.isActive=false);
      //重新赋值
      // this.setData({tabs})
      //子向父传递
      this.triggerEvent('Itemindex',index)
    }
  }
})

组件之Tabs.json文件

{
  "component": true,
  "usingComponents": {}
}

组件之Tabs.wxml文件

<!--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 class="title_item {{item.isActive?'active':''}}"  wx:for="{{tabs}}" wx:key="id"  bindtap="hendleTabs" data-index="{{index}}">{{item.name}}</view>
 </view>
 <view class="tabs_content">
 <!-- 占位符, -->
  <slot></slot>
 </view>
</view>

组件之Tabs.wxss文件

/* components/Tabs/Tabs.wxss */
.tabs{}
.tabs_title{
  display: flex;
  padding: 10rpx;
}
.title_item{
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
.active{
  color: red;
  border-bottom: 5rpx solid currentColor;  
}
.tabs_content{}

页面demo3.js文件

// pages/demo03/demo03.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabs:[
      {
        id:0,
        name:"首页",
        isActive:true
      },
      {
        id:1,
        name:"原创",
        isActive:false
      },
      {
        id:2,
        name:"分类",
        isActive:false
      },
      {
        id:3,
        name:"关于",
        isActive:false
      },
    ]
  },
  handleItemindex(e){
    const index = e.detail
    // console.log(index)
    let tabs = JSON.parse(JSON.stringify(this.data.tabs))
    // console.log(tabs)
    tabs.forEach((v,i)=>i===index?v.isActive=true:v.isActive=false);
    this.setData({
      tabs:tabs
    })
  },
})

页面之demo03.json文件

{
  "usingComponents": {
    "Tabs":"../../components/Tabs/Tabs"
  }
}

页面之demo03.wxml文件

<!-- 父向子通过属性传递数据 -->
<Tabs tabs="{{tabs}}" bindItemindex="handleItemindex">
<!-- 根据数据参数显示不同页面 -->
 <block wx:if="{{tabs[0].isActive}}">0</block>
 <block wx:elif="{{tabs[1].isActive}}">1</block>
 <block wx:elif="{{tabs[2].isActive}}">2</block>
 <block wx:else>3</block>
</Tabs>

样式图

 

posted on 2020-05-08 15:17  痴人谈情  阅读(288)  评论(0编辑  收藏  举报