微信小程序 wepy父子组件传值

在开发过过程中经常会有些重复的性的工作,为了加快我们的开发效率,便把一些相同的部分抽取出来,哪里用就扔哪里

 先讲一下组件的抽取

因为tab栏比较常用,就简单举例说明一下tab的抽取方法吧

建一个与page同级的文件夹,comments ,在此文件夹下新建一个 tabBar.wpy 页面  (结构为 wepy component)

1. 将抽取的结构放在tabBar.wpy 的 template里

<template>
      <!-- 顶部区域 -->
    <view class="tab-bar">
      <block wx:for="{{tabList}}" wx:key="">
        <view @tap="selectItem({{index}})" class="item {{selectIndex==index?'active':''}}">{{item}}</view>
      </block>
    </view>
</template>

2. 将样式放在tabBar.wpy的style里

<style lang='less'>

.tab-bar {
  height: 100rpx;
  background-color: white;
  display: flex;
  .item {
    flex: 1; //
    text-align: center;
    line-height: 100rpx;
    font-size: 32rpx;
    &.active {
      color: #eb4450;
      position: relative;
      &::after {
        content: '';
        position: absolute;
        width: 100%;
        height: 12rpx;
        background-color: #eb4450;
        bottom: 0;
        left: 0;
      }
    }
  }
}
</style>

3. 在需要用到的页面的 script里引入抽取的组件

<script>
import wepy from 'wepy'
// 引入自己的抽取的组件(不需要后缀名)
import tabBar from '../comment/tabBar'

4. 在用到的页面里声明一个组件(script 下面的 components)

 components = {
        tabBar:tabBar
    }

5. 在使用组件的地方放上一个tabBar标签 (放上的标签名就是comments 里的键)

  <tabBar></tabBar>

以上就是简单的组件抽取

二 静态传值(数据不写死,父往子传值)

1. 静态传值 (在子组件的script 中声明如下)

// child.wpy
props = {
    title: String // 只能穿字符串类型
};
onLoad () {
    console.log(this.title); // mytitle
}

 在父组件中

<tabBar title="mytitle">{{title}}</tabBar> 就可以看到这句话了

2. 动态传值(在子组件中)

 props = {
    // 动态传值 类型可以是很多 但是需要自己设置
tabList: {
type: Array, default: [] } }

在父组件中

 <tabBar title="mytitle" :tabList.sync="parentTitle"></tabBar>
 data = {
        parentTitle: ['标题1','标题2','标题3','标题4']
    }

再返回子组件中 之前写死的样式可以修改下

<block wx:for="{{tabList}}" wx:key="">
<view @tap="selectItem({{index}})" class="item {{selectIndex==index?'active':''}}">{{item}}</view> </block>

3. 双向传值 (下面的颜色是要一一对应的)

子组件中

props = {
    // 双向传值
    selectIndex: {
      type: Number,
      default: 0,// 设定选中项
      // 双向 这里必须制定 true
      twoWay: true
    }
  }
   <view @tap="selectItem({{index}})" class="item {{selectIndex==index?'active':''}}">{{item}}</view>

父组件中

 <tabBar title="mytitle" :selectIndex.sync="parentTitle"></tabBar>
 data = {
        selectIndex: 2, 默认选中项  这里我选2 n那么一进去就选择的是 标题2
        parentTitle: ['标题1','标题2','标题3','标题4']
    }

下面这是在子组件中设置点击切换tab栏功能(带颜色的是要绑定的,才能实现切换)

 methods = {
    selectItem(index) {
      console.log(index)
      this.selectIndex = index
    }
  }
<block wx:for="{{tabList}}" wx:key="">
        <view @tap="selectItem({{index}})" class="item {{selectIndex==index?'active':''}}">{{item}}</view>
  </block>





  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值