小程序篇 -- 父組件與子組件之間的傳值


1、父組件傳遞給子組件值,首先在components 中新建一個testComponents子組件,代碼如下:

testComponents.wxml

<view>
   <text>{{value}}</text>
</view>

testComponents.js

Component({
  /**
   * 組件的屬性列表
   */
  properties: {
    value:{
      type:String, //指定傳過來的值的類型
      value:0 //默認值,假如沒有值傳過來,value就會顯示默認值
    }
  },

})

2、接下來我們新建一個index父組件,對應代碼如下:

index.json

{
  "usingComponents": {
    "testComponent":"../../components/testComponent/testComponent"   //子組件的路勁
  }
}

index.wxml

<view >
  <testComponent value="張三"></testComponent>
</view>

3、運行index父組件得到的效果圖如下(假如value值沒傳,那么內容就會顯示為默認值:0):

4、子組件傳遞給父組件值,還是用上面的子組件,代碼如下:

testComponent.wxml

<view>
  <button bindtap="testClick">點擊傳遞給父組件值</button>
</view>

testComponent.js

Component({
 
  /**
   * 組件的方法列表
   */
  methods: {
    testClick(){
      //triggerEvent可以理解為vue中$emit
      this.triggerEvent("myevent","張三")
    }
  }
})

5、還是用上面的父組件,代碼如下:

index.json

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

index.js

Page({
  data:{
    value:null
  },
  thismyevent(e){
    // e.detail = 子組件傳遞過來的值
    this.setData({
      value:e.detail
    })
  }
})

index.wxml

<view >
  <testComponent bindmyevent="thismyevent"></testComponent>
  <text style="display: flex;justify-content:center;">{{value}}</text>
</view>

6、點擊按鈕得到子組件傳遞過來的張三,運行代碼得到的效果圖如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM