【微信小程序】自定义组件 - behaviors

1. 什么是 behaviors

在这里插入图片描述

2. behaviors 的工作方式

在这里插入图片描述

3. 创建 behavior

调用 Behavior(Object object) 方法即可创建一个共享的 behavior 实例对象,供所有的组件使用:
在这里插入图片描述

4. 导入并使用 behavior

在这里插入图片描述
在这里插入图片描述

5. behavior 中所有可用的节点

在这里插入图片描述

6. 同名字段的覆盖和组合规则*

在这里插入图片描述

关于详细的覆盖和组合规则,大家可以参考微信小程序官方文档给出的说明:
https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/behaviors.html

附:官方文档-behaviors

behaviors 是用于组件间代码共享的特性,类似于一些编程语言中的 “mixins” 或 “traits”。

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

详细的参数含义和使用请参考 Behavior 参考文档

组件中使用

组件引用时,在 behaviors 定义段中将它们逐个列出即可。

代码示例:

在开发者工具中预览效果

// my-component.js
var myBehavior = require('my-behavior')
Component({
  behaviors: [myBehavior],
  properties: {
    myProperty: {
      type: String
    }
  },
  data: {
    myData: 'my-component-data'
  },
  created: function () {
    console.log('[my-component] created')
  },
  attached: function () { 
    console.log('[my-component] attached')
  },
  ready: function () {
    console.log('[my-component] ready')
  },
  methods: {
    myMethod: function () {
      console.log('[my-component] log by myMethod')
    },
  }
})

在上例中, my-component 组件定义中加入了 my-behavior

my-behavior 结构为:

// my-behavior.js
module.exports = Behavior({
  behaviors: [],
  properties: {
    myBehaviorProperty: {
      type: String
    }
  },
  data: {
    myBehaviorData: {}
  },
  attached: function(){},
  methods: {
    myBehaviorMethod: function(){}
  }
})
  • 属性:myBehaviorProperty
  • 数据字段:myBehaviorData
  • 方法:myBehaviorMethod
  • 生命周期函数:attachedcreatedready

这将使 my-component 最终结构为:

  • 属性:myBehaviorPropertymyProperty
  • 数据字段:myBehaviorDatamyData
  • 方法:myBehaviorMethodmyMethod
  • 生命周期函数:attachedcreatedready

当组件触发生命周期时,上例生命周期函数执行顺序为:

  1. [my-behavior] created
  2. [my-component] created
  3. [my-behavior] attached
  4. [my-component] attached
  5. [my-behavior] ready
  6. [my-component] ready

详细规则参考 同名字段的覆盖和组合规则

同名字段的覆盖和组合规则

组件和它引用的 behavior 中可以包含同名的字段,对这些字段的处理方法如下:

  • 如果有同名的属性 (properties) 或方法 (methods):
    1. 若组件本身有这个属性或方法,则组件的属性或方法会覆盖 behavior 中的同名属性或方法;
    2. 若组件本身无这个属性或方法,则在组件的 behaviors 字段中定义靠后的 behavior 的属性或方法会覆盖靠前的同名属性或方法;
    3. 在 2 的基础上,若存在嵌套引用 behavior 的情况,则规则为:引用者 behavior 覆盖 被引用的 behavior 中的同名属性或方法。
  • 如果有同名的数据字段 (data):
    • 若同名的数据字段都是对象类型,会进行对象合并;
    • 其余情况会进行数据覆盖,覆盖规则为: 引用者 behavior > 被引用的 behavior靠后的 behavior > 靠前的 behavior。(优先级高的覆盖优先级低的,最大的为优先级最高)
  • 生命周期函数和 observers 不会相互覆盖,而是在对应触发时机被逐个调用:
    • 对于不同的生命周期函数之间,遵循组件生命周期函数的执行顺序;
    • 对于同种生命周期函数和同字段 observers ,遵循如下规则:
      • behavior 优先于组件执行;
      • 被引用的 behavior 优先于 引用者 behavior 执行;
      • 靠前的 behavior 优先于 靠后的 behavior 执行;
    • 如果同一个 behavior 被一个组件多次引用,它定义的生命周期函数和 observers 不会重复执行。

我的代码

在这里插入图片描述

<!--component/myComponent/myComponent.wxml-->
<text>component/myComponent/myComponent.wxml</text>
<text>components/my-component/my-component.wxml</text>
<view>我是my-component</view>
-----------------------不同----
<view>myComponent里的</view>
<button bindtap="myMethod"> myMethod</button>
<view>data数据--myData:{{myData}}</view>
<view>properties数据--myProperty:{{myProperty}}</view>
<view>Behavior里的</view>
<view>data数据--myBehaviorData:{{myBehaviorData}}</view>
<view>properties数据--myBehaviorProperty:{{myBehaviorProperty}}</view>
<button bindtap="myBehaviorMethod">myBehaviorMethod</button>
---------------------相同----------------------------
<view>相同的属性</view>
<view>strTest:{{strTest}}</view>
<view>相同的数据</view>
<view>myObject:{{myObject.username}}--{{myObject.age}}</view>
<view>相同的方法</view>
<button bindtap="commonMethod"> commonMethod</button>
// components/my-component/my-component.js
const myBehavior = require('../../behaviors/my-behaviors')
Component({
  behaviors: [myBehavior],
  properties: {
    myProperty: {
      type: String,
      value: 'myComponent'
    },
    strTest:{
      type: String,
      value: 'my-component'
    }
  },
  data: {
    myData: 'my-component-data',
    myObject:{
      username:'[my-component] zhangsan'
    }
  },
  created: function () {
    console.log('[my-component] created')
  },
  attached: function () { 
    console.log('[my-component] attached')
  },
  ready: function () {
    console.log('[my-component] ready')
  },
  methods: {
    myMethod: function () {
      console.log('[my-component] log by myMethod')
    },
    commonMethod(){
      console.log("我是myComponent"); 
    }
  }
})

// my-behaviors.js
module.exports = Behavior({
  behaviors: [],
  properties: {
    myBehaviorProperty: {
      type: String,
      value: 'myBehaviorProperty'
    },
    strTest:{
      type:String,
      value:'Behavior'
    }
  },
  data: {
    myBehaviorData: "myBehaviorData",
    myObject:{
      username:"张三",
      age:20
    }
  },
  created: function () {
    console.log('[behavior] created')
  },
  attached: function () { 
    console.log('[behavior] attached')
  },
  ready: function () {
    console.log('[behavior] ready')
  },
  methods: {
    myBehaviorMethod: function(){
      console.log('myBehaviorMethod');
    },
    commonMethod(){
      console.log("我是behavior"); 
    }
  }
})

结果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

<think>嗯,用户现在问的是微信小程序自定义组件的引用。之前他们问了原生环形进度条的实现,现在转向了自定义组件,可能是因为在实现进度条时遇到了复用的问题,想要了解如何更高效地组织代码。 首先,我需要确认用户的需求。他们可能已经尝试过用原生组件实现,但发现在多个页面重复使用时代码冗余,维护起来麻烦。这时候自定义组件就能派上用场了,可以封装功能,方便复用。 接下来,我需要回忆微信小程序自定义组件的基本结构。通常包括四个文件:json、wxml、wxss和js。用户需要知道如何创建这些文件,并在页面中正确引用。可能需要详细说明每个文件的作用,比如json中的component声明,以及如何配置属性。 然后,用户可能关心的是组件之间的通信方式。比如,如何通过properties传递数据,如何在组件内部触发事件,父页面如何监听这些事件。这里需要举例子,比如进度条的百分比传递和完成事件的触发。 另外,样式的隔离也是一个常见问题。微信小程序默认有样式隔离,但用户可能需要覆盖组件样式,这时候需要解释addGlobalClass选项的使用方法,以及外部如何传递样式类。 还有,用户可能想知道如何使用第三方组件,比如Vant WeUI,这部分需要简单提及,并给出配置usingComponents的例子。 最后,注意事项部分需要提醒用户路径的正确性、生命周期函数的使用、调试方法以及性能优化点。比如组件生命周期和页面的不同,高频更新时的优化建议。 在组织回答时,要保持结构清晰,分步骤说明创建、引用、通信、样式处理等,并给出代码示例,让用户能一步步跟着操作。同时,注意与之前的回答保持连贯,比如提到之前环形进度条可以封装为组件,增强用户的连接感。</think>微信小程序自定义组件引用可分为以下六个核心步骤,通过案例形式说明实现过程: 一、组件创建规范 1. 文件结构要求: ``` components/ ├─ my-component/ // 组件目录 │ ├─ my-component.js // 组件逻辑 │ ├─ my-component.json // 组件声明 │ ├─ my-component.wxml // 组件模板 │ └─ my-component.wxss // 组件样式(可选) ``` 二、组件声明配置 ```json // components/my-component/my-component.json { "component": true, "usingComponents": {} // 若需嵌套子组件可在此声明 } ``` 三、组件模板开发 ```wxml <!-- components/my-component/my-component.wxml --> <view class="custom-component"> <slot name="header"></slot> <!-- 具名插槽 --> <text>{{innerText}}</text> <slot></slot> <!-- 默认插槽 --> </view> ``` 四、组件逻辑实现 ```javascript // components/my-component/my-component.js Component({ properties: { innerText: { // 对外暴露的属性 type: String, value: '默认文字' } }, data: { privateData: '组件私有数据' }, methods: { customMethod() { // 组件内部方法 this.triggerEvent('customevent', { detail: '事件数据' }) } } }) ``` 五、宿主页面引用方法 1. 页面配置声明: ```json // pages/index/index.json { "usingComponents": { "my-component": "/components/my-component/my-component" } } ``` 2. 页面模板使用: ```wxml <!-- pages/index/index.wxml --> <my-component inner-text="动态内容" bind:customevent="handleEvent" > <view slot="header">自定义头部</view> <view>默认插槽内容</view> </my-component> ``` 六、样式处理技巧 1. 启用全局样式继承(组件配置): ```javascript Component({ options: { addGlobalClass: true // 允许外部样式影响组件 } }) ``` 2. 外部样式穿透: ```wxss /* pages/index/index.wxss */ .custom-component .inner-text { color: #07c160; /* 影响组件内部元素 */ } ``` 扩展应用场景: 1. 第三方组件库引用(如Vant WeUI): ```json { "usingComponents": { "van-button": "@vant/weapp/button/index" } } ``` 注意事项: 1. 路径规范:建议使用绝对路径`/components/...`避免相对路径混乱 2. 生命周期差异:组件使用`lifetimes`配置替代Page生命周期 3. 通信限制:避免直接修改父页面数据,建议使用事件传递 4. 调试技巧:通过`wx.createSelectorQuery().in(this)`获取组件节点信息 5. 性能优化:高频更新组件建议使用`pureDataPattern`指定纯数据字段 通过组件化开发可实现代码复用率提升40%-60%,建议将通用功能(如您之前提到的环形进度条)封装为组件库。复杂组件建议结合`behaviors`实现代码复用,跨组件通信可使用`getCurrentPages()`获取页面栈或全局事件总线。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值