微信小程序 组件传递

组件传递

Created: Sep 12, 2020 4:36 PM
分类: 组件

父传子

写上父标签需要用到的属性

<Tabs tabs="{{tabs}}" bindtabsItemChange="handleTabsItemChange">

在父标签的json文件中定义属性

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

在子组件中接收属性

Component({
    properties: {
        tabs:{
            type:Array,
            value:[]
        }
    }
});

使用相关属性

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

子组件触发父组件事件

先把标签绑定一个事件

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

在子组件写一个方法,传递事件名,参数

methods: {
        handleItemTap(e){
            const {index}=e.currentTarget.dataset
            this.triggerEvent("tabsItemChange",{index})
        }
    }

在父组件绑定相关的事件

<Tabs tabs="{{tabs}}" bindtabsItemChange="handleTabsItemChange">

接收传递过来的参数,进行

/**
     * 处理激活样式
     * @param e 参数
     */
    handleTabsItemChange(e) {
        const {index} = e.detail
        let {tabs} = this.data
        tabs.forEach((v, i) => i == index ? v.isActive = true : v.isActive = false)
        this.setData({
            tabs
        })
    }
posted @ 2020-09-19 11:24  彼_岸  阅读(338)  评论(0编辑  收藏  举报