以前在學習小程序的過程當中遇見了很多問題,在這裏彙總記錄一下,本篇爲第一篇。
1.小程序中切換tab傳值/通訊問題
這是切換
tab碰見的問題,
應用情景:每次點擊某一tab時傳入設定值。
因爲小程序每個頁面都是獨立的個體,那麼須要經過一個全局的東西來保存值。小程序提供了惟一的一個
全局的應用實例,能夠經過
getApp()
來獲取。這樣只要把變量保存到實例中,在另外一個頁面去獲取就能夠了。
// 頁面一 page1.js
var app = getApp();
Page({
data: {
num: 1,
...
},
change: function () {// 某綁定事件
this.setData({num: this.data.num + 1});
app.num = this.data.num;
},
onLoad: function () {
app.num = this.data.num;
}
})
// 頁面二 page2.js
var app = getApp();
Page({
data: {
xxx: xxx
...
},
onShow: function () {
console.log(app.num);// 打印保存早全局變量中的值
}
})
2.小程序中點擊時傳值
在綁定事件的標籤上添加一個
data-xx
屬性,接着在事件中獲取。
// page.wxml
...
<view data-num="1" bindtap="click"></view>
// page.js
Page({
data: {
xxx: xxx
...
},
click: function (e) {
console.log(e.currentTarget.dataset.num);// 打印傳來的值
}
})
3.小程序中點擊時爲點擊的對象添加選中樣式
// page.wxml
...
<view class="item-style {{showIndex === item ? 'active' : ''}}"
wx:for="{{data}}"
wx:key="index"
data-index="{{item}}"
bindtap="click"
>
{{item}}
</view>
// page.js
Page({
data: {
data: [1, 2, 3, 4],
showIndex: '',
...
},
click: function (e) {
this.setData({showIndex: e.currentTarget.dataset.index});
}
})
// page.wxss
...
.item-style.active {
background-color: #F5F5F5;
}
4.小程序配置tabBar
配置tabBar的選中樣式要在外一層,以前不知道,覺得每個均可以配。。。
// app.json
...
"tabBar": {
"color": "#000",// 默認樣式
"selectedColor": "#3C5F81",// 選中樣式
"borderStyle": "white",// "white" or "black" 有無分隔線
"list": [
{
"pagePath": "pages/page1/page1",
"iconPath": "images/tab/page1.png",
"selectedIconPath": "images/tab/page1-s.png",
"text": "頁一"
},
{
"pagePath": "pages/page2/page2",
"iconPath": "images/tab/page2.png",
"selectedIconPath": "images/tab/page2-s.png",
"text": "頁二"
}
]
}
...
一個能夠查詢天氣的小程序源碼git