首页 > 编程知识 正文

微信小程序自定义组件传值,微信小程序自定义组件生命周期

时间:2023-05-05 22:06:19 阅读:258422 作者:3743

behaviors

每个 behavior 可以包含一组属性、数据、生命周期函数和方法。组件引用它时,它的属性、数据和方法会被合并到组件中,生命周期函数也会在对应时机被调用。 每个组件可以引用多个 behavior ,behavior 也可以引用其它 behavior 。


behaviors简单使用的案例

创建一个my-behavior.js

// my-behavior.jsmodule.exports = Behavior({ properties: { // 默认颜色 color: { type: String, value: 'blue' } }, data: { }, methods: { // 改变按钮颜色 changeColor(e) { const {color} = e.currentTarget.dataset; this.setData({ color }) } }})

组件中引入behaviors

// components/my-component/my-component.js// 引入my-behavior.jsvar myBehavior =require("../my-behavior");Component({ behaviors: [myBehavior]})

组件页面结构

<!--components/my-component/my-component.wxml--><!-- behavior --><view>{{color=='blue' ? '默认颜色是blue': '颜色被修改了'+ color}}</view><button bindtap="changeColor" data-color="pink" style="color:{{color}}">behavior-{{color}}</button>

页面中使用组件

<!--pages/index/index.wxml--><my-component id="myComponent" ></my-component>

默认

点击按钮后颜色改变


需要注意

1 组件中同名的属性和方法会覆盖behaviors 。
2 组件中引入多个behaviors,在数组中位置靠后的会覆盖前面的。
3 组件中同名的属性如果是数据类型会和behaviors的合并(behaviors[1,2] 组件 [3,4] 结果 [1,2,3,4]),非数据类型是覆盖。


内置 behaviors

自定义组件可以通过引用内置的 behavior 来获得内置组件的一些行为。

表单使用案例: wx://form-field

wx://form-field 使自定义组件有类似于表单控件的行为。 form 组件可以识别这些自定义组件,并在 submit
事件中返回组件的字段名及其对应字段值,以{name:value}的形式返回。

Component({ behaviors: ['wx://form-field'], lifetimes:{ // 在组件实例进入页面节点树时执行 attached(){ this.setData({ value: 'behaviors-value' }) } },})

引用组件的页面

<!--pages/index/index.wxml--><form bindsubmit="handlesubmit"> <custom-form-field name="behavior-name"></custom-form-field> <button form-type="submit">点我</button></form> // pages/index/index.jsPage({ submit(e){ console.log(e.detail.value) }})

返回结果


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。