微信小程式動態設定/獲取值與屬性
阿新 • • 發佈:2019-02-05
這兩天在公司做微信小程式,也是剛剛入手,遇到了很多的坑,和大家分享一下。
首先微信小程式不像普通的頁面一樣,獲取屬性啊什麼的需要你去操作節點,在小程式裡你就是去對這個頁面的data進行一系列的操作,然後通過data來反映到頁面上。
1.設定data與使用data
wxml程式碼:
<!--index.wxml-->
<view class="container" style='color:{{color}}'>
{{motto}}
</view>
js程式碼:
Page({ data: { motto: 'Hello World', color:'red' }, })
截圖:
這是最簡單的使用流程。
2.通過js獲取與設定data的值
js程式碼:
Page({
data: {
motto: 'Hello World',
color:'red'
},
onLoad: function () {
console.log(this.data.motto)
this.setData({
motto:'hello hadar'
})
},
})
截圖:
這裡需要注意一下,設定值的時候只能用setData, 不能this.data.motto=‘xxxxx’ ,通過這樣設定的data,確實修改了值,但是不會反應到wxml頁面中去。
錯誤示範:
3.當多個元素呼叫相同的函式對相對應的資料進行處理
比如說,我有三個input,我需要失去其焦點的時候,儲存對應輸入的資料到data中,可不能傻傻的去寫三個函式吧。
wxml程式碼:
<input data-id='input1' bindblur='moveTo'></input>
<input data-id='input2' bindblur='moveTo'></input>
<input data-id='input3' bindblur='moveTo'></input>
這裡需要用到data-xx 來標識當前的元素。
js程式碼:
Page({
data: {
motto: 'Hello World',
color:'red'
},
moveTo:function(e){
console.log(e)
var x={}
x[e.currentTarget.dataset.id]=e.detail.value
this.setData(x)
console.log(this.data)
}
})
這裡值得一提的是在setData之前建立一個物件,將需要儲存的引數與引數值先傳入進去,不然在setData中是無法使用變數來對引數名進行操作的。這在request中對data進行遍歷的時候也會常常用到。切記在setdata之前把物件拼接好。
執行截圖:
4.點選一個元素對另一個元素進行一定的操作
wxml:
<input data-id='input1' hidden='{{hidden}}' ></input>
<input data-id='input2' bindtap='show'></input>
js:
Page({
data: {
motto: 'Hello World',
color:'red',
hidden:''
},
show:function(){
this.setData({
hidden:'true'
})
}
})
用法還有很多,這裡也就舉幾個例子,大家如果有什麼更好的方法歡迎留言交流。
最後再提一下,很多時候會在函式內部呼叫一些方法,這時候一定要注意this對應著誰。最好在開始定義一個var that=this,先把this儲存下來,避免發生錯誤。