Long time no see, somehow I find something I should write down so that I may get started quickly next time.
This is the doc
Focus
- Structure of the constructor
- The Data Streaming of comps
- Lifetime of comps
- eg and some points
Structure
- Using pubic behavior(Optional)
behaviors: [myBehavior]
Not only in comps, but also in every behaviors.
what is behavior
If want to DIY the export of component or whatever, you could use
内置behavior
like wx://component-export which just like a plug-in
- State private data and inherited property from father page
//in comp
properties: {
myProperty: {
type: String
}
},
data: {
myData: 'my-component-data'
},
//in page.html
<my-component myProperty="Initial Value"/>
- LifeTime function
reated attached detached
Note that the behavior life time has a higer level than the component
组件实例刚刚被创建好时, created 生命周期被触发。此时,组件数据 this.data 就是在 Component 构造器中定义的数据 data 。 此时还不能调用 setData 。 通常情况下,这个生命周期只应该用于给组件 this 添加一些自定义属性字段。
在组件完全初始化完毕、进入页面节点树后, attached 生命周期被触发。此时, this.data 已被初始化为组件的当前值。这个生命周期很有用,绝大多数初始化工作可以在这个时机进行。
在组件离开页面节点树后, detached 生命周期被触发。退出一个页面时,如果组件还在页面节点树中,则 detached 会被触发
- methods
No need to say
Example
// my-component.js
const app = getApp()
var myBehavior = require('my-behavior')
Component({
// 若需要自定义 selectComponent 返回的数据,可使用内置 behavior: wx://component-export 从基础库版本 2.2.3 开始提供支持。
//the diy value export to outside
// behaviors: ['wx://component-export'],
// export: function() {
// return { key1: 'I from comp' }
// },
//pubic code
behaviors: [myBehavior],
// state the property sent from page.html
properties: {
myProperty: {
type: String
}
},
//private property
data: {
myData: 'my-component-data'
},
//lifetime func
created: function () {
console.log('[my-component] created')
},
attached: function () {
console.log('[my-component] attached')
this.setData({
myData: app.globalData.globalMsg
})
// let msg = app.globalData.globalMsg
// console.log("Get data from global: "+msg)
},
ready: function () {
console.log('[my-component] ready')
},
//the methods you can bind in component.wxml
methods: {
myMethod: function () {
console.log('[my-component] log by myMethod')
let msg = 'I am details from methods of comp'
//this would bind in page.html
this.triggerEvent("ringComp",msg)
},
outputmethod(){
console.log('now is called from comp and my private data is'+this.data.myData)
}
},
})
//in page.html
<view>
<my-component id= 'the-id' my-behavior-property="behavior-property" my-property="my-property" bindringComp="typerComp" bindringBehavior="typerBeha">
<button bindtap="typerSlot">this is a slot</button>
</my-component>
</view>
//in page.js
typerSlot(){//bind to the button in slot
let that = this.selectComponent('#the-id')
console.log(that)//get this from component
this.selectComponent('#the-id').outputmethod()//Execute the method inside
},
Data Streaming
好家伙 懒得写了 反正就这样