使用在需要使用的页面,用的json文件中的usingComponents对象
- 组件使用名 : 路径
- 组件json文件中加入"component": true
插槽slot(原理同vue)
- 多插槽用name
- 禁止使用插槽,在组件的js中,使用
options: {
multipleSlots: true // 在组件定义时的选项中启用多slot支持
}
页面往组件传值,properties(与data同级)接收
- 组件为header,在页面
<header str="str1"></header>
- 组件js中,properties{str:String}
页面触发组件事件
- 组件为header,在页面
<header id="header"></header>
,页面js,通过this.selectComponent("#header").show() - 组件js中,method:{ show(){ … } }
组件触发页面事件
- 组件名为header组件,组件中,
<view id="click"></view>
,js中,
methods:{ click(){ this.triggerEvent("show") } }
// this.triggerEvent("show",123,321) 123和321是传的值
- 页面中,
<header bind:show="wx"></header>
,js中,wx(与data同级),wx(){ };
组件中,data
- data定义的只能:私有数据,可用于模板渲染
组件中的behavior
let SmallFourBeh = Behavior({ // 实例一个Behavior
properties: { // 共享属性
},
data:{ // 共享数据
},
methods:{ // 共享方法
}
})
export { SmallFourBeh } // 导出Behavior
- 组件中接收使用,
import { SmallFourBeh } from './Behavior.js'
,behaviors: [SmallFourBeh]
(与data同级)
observers监听数据
- 数据监听器可以用于监听和响应任何属性和数据字段的变化。从小程序基础库版本 2.6.1 开始支持。
- 使用
observers: {
'numberA, numberB': function (numberA, numberB) {
this.setData({
sum: numberA + numberB
})
}
}
组件中的生命周期
Component({
properties:{
innerText:{
type:String
}
},
data:{
},
methods:{
},
created:function(){
// 组件生命周期函数,在组件实例进入页面节点树时执行,注意此时不能调用setData
console.log('Component-1 >> created');
},
attached:function(){
// 组件生命周期函数,在组件实例进入页面节点树时执行。
console.log('Component-1 >> attached');
},
ready:function(){
// 在组件布局完成后执行,此时可以获取节点信息
console.log('Component-1 >> ready');
},
moved:function(){
// 在组件实例被移动到节点树另一个位置时执行
console.log('Component-1 >> moved');
},
detached:function(){
// 在组件实例被从页面节点树移除时执行
console.log('Component-1 >> detached');
},
lifetimes:{
// 组件生命周期声明对象,将组件的生命周期收归到该字段进行声明,原有声明方式仍旧有效,如同时存在两种声明方式,则lifetimes字段内声明方式优先级最高
created:function(){
console.log('Component-1 lifetimes >> created');
},
attached:function(){
console.log('Component-1 lifetimes >> attached');
},
ready:function(){
console.log('Component-1 lifetimes >> ready');
},
moved:function(){
console.log('Component-1 lifetimes >> moved');
},
detached:function(){
console.log('Component-1 lifetimes >> detached');
}
},
pageLifetimes:{
// 组件所在页面的生命周期声明对象,目前仅支持页面的show和hide两个生命周期
show:function(){
console.log('Component-1 pageLifetimes >> Show');
},
hide:function(){
console.log('Component-1 pageLifetimes >> Hide');
}
}
})
更详细请看:https://github.com/qq8344310/wechat-miniProgram-demo