微信小程序 定義全局數據、函數復用、模版等
微信小程序定義全局數據、函數復用、模版等問題總結:
1.如何定義全局數據
在app.js的App({})中定義的數據或函數都是全局的,在頁面中可以通過var app = getApp(); app.function/key的方式調用,不過我們沒有必要再app.js中定義全局函數。
2.如何實現代碼的復用
函數的復用:
test.js
test: function(){
}
module.exports={
test:test
}
other.js
var common = require('test.js');
page({
common.test()
})
模板:
<template name="odd">
<view> odd </view>
</template>
<template name="even">
<view> even </view>
</template>
<block wx:for="{{[1, 2, 3, 4, 5]}}">
<template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/>
</block>
//我們頁可以把模板定義在其他文件中,以<import src="url"/>的形式引入,但是import有作用域的概念,即只會import目標文件中定義的template,
而不會import目標文件import的template
//include可以將目標文件除了<template/>的整個代碼引入,相當於是拷貝到include位置。
3.對於組件中值為boolean類型的屬性,比如progress組件的active屬性,checkbox的checked屬性等等。無論設置成true還是false該屬性都生效,測試發現html中也有這種情況,但通過checked={{}}的方式可以渲染成功。
轉載~