天天看點

小程式元件傳值通訊

學習vue或者react的同學都知道 元件之間是可以進行傳值通訊的 對于剛剛接觸小程式的同學而言 可能不知道 和vue傳遞方式幾乎是一樣的 會vue的同學應該很 容易了解 下面就帶着同學們一起來看下吧

假設有一個parent和一個child 

首先看下parent裡面的代碼吧

//parent.wxml

<tabs tabs="{{tabs}}" bindchangeTab="changeTab">
  <block>
    <view wx:if="{{tabs[0].isActive}}">111</view>
    <view wx:elif="{{tabs[1].isActive}}">222</view>
    <view wx:elif="{{tabs[2].isActive}}">333</view>
    <view wx:else="{{tabs[3].isActive}}">444</view>
  </block>
</tabs>

//parent.js

Page({
  /**
   * 頁面的初始資料
   */
  data: {
    //傳遞給子元件
    tabs:[
      {
        index:0,
        label:'首頁',
        isActive:true
      },
      {
        index:1,
        label:'關于',
        isActive:false
      },
      {
        index:2,
        label:'其他',
        isActive:false
      },
      {
        index:3,
        label:'我的',
        isActive:false
      },
    ]
  },
    //接受子元件傳遞的資料
  changeTab(e){
    let index = e.detail
    let {tabs} =this.data
    tabs.map((item,i)=>i===index ? item.isActive = true : item.isActive = false)
    this.setData({
      tabs
    })
  }
})

//parent.json

{
  "usingComponents": {
    "tabs":"../../components/parent/parent"
  }
}
           

接着 我們看下child的代碼

//child.wxml
<view class="tabs">
  <view bindtap="changeTab" data-index="{{index}}" class="tabs_item {{item.isActive?'active':''}}" wx:for="{{tabs}}" wx:key="index">{{item.label}}</view>
</view>
<view>
  <slot></slot>
</view>

//child.js
Component({
  /**
   * 元件的屬性清單
   */
   //接收父元件的資料
  properties: {
    tabs:{
      type:Array,
      value:[]
    }
  },

  /**
   * 元件的方法清單
   */
  methods: {
    //傳遞給父元件
    changeTab(e){
      let { index } = e.currentTarget.dataset
      this.triggerEvent("changeTab",index)
    }
  }
})
           

總結 :

一:父元件傳給子元件 

1.首先在父元件 .json 進行配置

2.父元件拿到配置标簽 直接當标簽進行使用

3.在子元件标簽上自定義屬性形式值為要傳遞的資料

4.子元件通過properties進行接收 

5.頁面直接使用接收的屬性

二:子元件傳給父元件

1.子元件通過triggerEvent 自定義參數及傳遞的資料

2.子元件标簽上通過自定義傳遞的事件 那後擷取事件源得到參數

對你有幫助的同學請點點贊 關注關注吧 後面會不定期更新新的内容及技術