關於微信小程序獲取多個formId的實現方法


在此之前,很多人使用過form和button的多層嵌套來實現點擊一次獲取多個formId的目的,如下圖所示,點擊一次“提交”,可以獲取到多個formId

但是在今年3月份,這個投機取巧的方法(算是微信的一個bug)已經被微信修復,那么再使用這個方法,所拿到的formId都是相同的了,也就不符合我們的需求了

 

 

接下來給大家介紹另一種方法:

將form和button封裝成組件模擬form submit,並把這個組件做成layout級,這樣可以把整個頁面包括在layout里面,利用事件自動冒泡的特性,只要點擊了頁面任一位置,就能獲取到formId

1. 新建一個組件layout,wxml、wxss、js、json代碼分別如下

<form bindsubmit="formSubmit" report-submit class="layout">
  <button formType="submit" class="button" hover-class="none">
    <view class="fixed"><slot></slot></view>
  </button>
</form>
.layout {
    display: inline-block;
    padding-left: 0;
    padding-right: 0;
    box-sizing: border-box;
    font-size: inherit;
    text-align: left;
    text-decoration: none;
    line-height: inherit;
    -webkit-tap-highlight-color: transparent;
    color: inherit;
    width: 100%;
    position: relative;
}
.layout .button{
    display: inline-block;
    padding-left: 0;
    padding-right: 0;
    box-sizing: border-box;
    font-size: inherit;
    text-align: left;
    text-decoration: none;
    line-height: inherit;
    -webkit-tap-highlight-color: #000;
    color: inherit;
    width: 100%;
    position: relative;
}
.layout .button .fixed{
    position:relative;
    z-index: 9999;
    width: 100%;
}
.layout .button:before,.layout .button:after{
    border-width: 0;
}
Component({
  methods: {
    formSubmit: function (e) {
      let formId = e.detail.formId
      console.log(formId)
    }
  }
})
{
  "component": true
}

 

2. 在app.json中,將layout添加為全局組件

"usingComponents": {
    "layout": "/components/layout/index"
  }

 

3. 在頁面中使用

<layout>
  <view class="container">
    ...
  </view>
</layout>

 


免責聲明!

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



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