微信小程序input獲取輸入參數


微信小程序input獲取輸入,如何獲取參數?

通常使用的是input的綁定方法

bindinput="userInput"
 
綁定的方法如下,通過e攜帶的detail.value獲取用戶的輸入
 
1. userInput(e) {
2.       this.setData({
3.           name : e.detail.value,
4.      })
5.  }
 
e為該方法觸發返回節點攜帶的參數,如果你想知道e是什么可以將起打印處理
 
1. console.log(e)
 
頁面input組件綁定獲取方法
<input class='name'   bindinput="userInput" maxlength="3" value="{{name}}" placeholder="輸入商品的名稱"></input>
 
那么對於頁面很多的input,是否需要每一個輸入對應一個方法呢?
 

其實只要一個就可以了,獲取對應的參數和用戶的值即可
獲取值的方式是e.detail.value;
 
獲取參數的方式呢?其實可以給 input攜帶參數id
<input class='name'  bindinput="userInput" 
id='name' 
maxlength="3" value="{{name}}" placeholder="輸入商品的名稱"></input>
<input class='price'  bindinput="userInput" 
id='price' 
maxlength="3" value="{{price}}" placeholder="輸入商品的價格"></input>
 
獲取節點對應的id為  e.target.id
 
這時上面的方法可以寫成
 
1. userInput(e) {
2.       let id = e.target.id;
3.       this.setData({
4.          [id] : e.detail.value,
5.      })
6.  }
 
或是這樣
 
1. userInput(e) {
2.       this.setData({
3.          [e.target.id] : e.detail.value,
4.      })
5.  }
 
這時同一個方法就可以分別獲取到商品的name和price輸入的值了
 
如果是要提交一個表單呢,所有參數都需要整個提交參數
 
這時提交時希望直接提交一個參數,而不是要整合,可以 把所有參數加到一個對象內即可,那如何獲取呢?
 
1.   this.setData({
2.        'args.id':   290
3.  })
 
通過上面的方式可以使data內的args的屬性id的值為290
 
那么就可以改進上面的方式獲取表單的值
<input class='name'  bindinput="userInput"  id='args.name' maxlength="3" value="{{args.name}}" placeholder="輸入商品的名稱"></input>
<input class='price'  bindinput="userInput"  id='args.price' maxlength="3" value="{{args.price}}" placeholder="輸入商品的價格"></input>
 
通過
1. userInput(e) {
2.       this.setData({
3.          [e.target.id] : e.detail.value,
4.      })
5.  }
 
獲取到用戶輸入的值直接存入args對象中
 
1.  args : {
2.       name: '金鑼',
3.       price: '23.99'
4. }
 
可以通過控制台查看參數變化

 

 當然

<textarea  placeholder="輸入商品的名稱" maxlength="60"  bindinput="userInput"  id='args.name'  value="{{args.name}}">  </textarea>
也適用
 
 
聲明: 由於知識面有限,難免有疏漏,懇請指出!


免責聲明!

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



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