写一个简单的小程序自定义封装组件demo
index.json
{
"usingComponents": {
"Component": "../components/component"
}
}
index.wxml
<Component str="{{str}}" bind:sendData="getComponentData"></Component>
index.js
Page({
data: {
str: 'Hello World',
},
onLoad: function () {
},
getComponentData(e) {
console.log(e.detail.content); // 子组件的值
}
})
这里是组件
component.josn
{
"component": true
}
component.wxml
<view class="wraper">
<view style="text-align: center; ">{{str}}</view>
<button bindtap="_SendData">给父组件传值</button>
</view>
component.js
Component({
properties: { // 接收父组件传来的数据
str: { // 数据名称
type: String, // 数据类型
value: "默认值" // 数据默认值
},
},
data: {
str: "" // 组件内数据
},
methods: {
/**
* sendData 必须和父组件一致
* {}:需要传的值
*/
_SendData() {
this.triggerEvent("sendData", {
content: "我是子组件"
})
},
},
lifetimes: {
// 当前组件生命周期
created: function () {
console.log("组件被创建");
},
attached: function () {
console.log("组件开始加载");
},
ready: function () {
console.log("组件加载完成");
},
moved: function () {
console.log("在组件实例被移动到节点树另一个位置时执行");
},
detached: function () {
console.log("在组件实例被从页面节点树移除时执行");
},
error: function () {
console.log("每当组件方法抛出错误时执行");
}
},
pageLifetimes: {
// 组件所在页面的生命周期
show: function () {
console.log("页面被展示");
},
hide: function () {
console.log("页面被隐藏");
},
resize: function (size) {
console.log("页面尺寸变化");
}
}
});
注意点:
- 自定义组件中css不能直接使用app.wxss中的公告样式。
- 组件内尽量不要改变父组件传来的数据。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。