写一个简单的小程序自定义封装组件democss
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); // 子组件的值 } })
这里是组件json
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("页面尺寸变化"); } } });
注意点:小程序