小程序 之页面获取自定义组件中的值

  1. 新建组件:在component下新建一个tabBar
    在这里插入图片描述
  2. 在组件的index.wxml中写如下代码:
<cover-view class="tab-bar">
	<cover-view class="tab-bar-border"></cover-view>
	<cover-view wx:for="{{list}}" wx:key="index" class="tab-bar-item" data-path="{{item.pagePath}}" data-index="{{index}}" bindtap="tabChange">
		<cover-image src="{{tabbarIndex === index ? item.selectedIconPath : item.iconPath}}"></cover-image>
		<cover-view style="color: {{tabbarIndex === index ? selectedColor : color}}">{{item.text}}</cover-view>
	</cover-view>
</cover-view>
  1. 在组件的index.js中写如下代码:
Component({
	properties: {
	    list: {
	      type: Array,
	      value: []
	    },
	    selectedColor:{
	      type: String,
	      value:''
	    },
	    color:{
	      type: String,
	      value:''
	    },
	  },
	data: {
	    tabbarIndex: 0//默认显示第一个tab元素
	  },
	methods: {
	    //组件的点击事件
	    tabChange(e) {
	      //获取到底部栏元素的下标
	      let index = e.currentTarget.dataset.index;
	      this.setData({
	        tabbarIndex:index,
	      })
	      //triggerEvent获取组件的事件
	      //onMyEvent 页面传过来的点击事件名称
	      this.triggerEvent('onMyEvent',{
	        tabbarIndex:index,
	      })
	    },
	  }
  })

在这里插入图片描述

  1. 在页面pages/index/index.json中加入
{
  "navigationBarTitleText": "测试",
  "usingComponents": {
    "mp-tabbar": "../components/tabBar/index"
  }
}
  1. 在页面pages/index/index.wxml中加入
<view wx:if="{{tabbarIndex == 0}}">111111</view>
<view wx:if="{{tabbarIndex == 1}}">222222</view>
<view wx:if="{{tabbarIndex == 2}}">333333</view>
<mp-tabbar list="{{list}}" id='tabComponent' bind:onMyEvent="switchTab"></mp-tabbar>

在这里插入图片描述

  1. 在页面pages/index/index.js中加入
//获取组件传递出来的数据
  switchTab:function(e){
    let index = e.detail.tabbarIndex;
    this.setData({
      tabbarIndex:index
    })
    console.log(e.detail.tabbarIndex)
  }

在这里插入图片描述

  1. 运行
    在这里插入图片描述
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值