小程序组件usingComponents的使用

微信   2025-01-06 11:36   76   0  

1. 创建自定义组件

首先,我们需要创建一个自定义组件。在项目的根目录下,创建一个新的文件夹用于存放这个组件,例如 my-component。在这个文件夹下,创建以下三个文件:

my-component.js

my-component.wxml

my-component.wxss


my-component.js 文件

Component({
  properties: {
    // 接收来自父组件的数据
    title: {
      type: String,
      value: '默认标题' // 默认值
    }
  },
  data: {},
  methods: {
    handleClick() {
      // 点击事件处理
      this.triggerEvent('myevent', { message: '来自自定义组件的消息' });
    }
  }
});


my-component.wxml 文件

<view>
  <text>{{title}}</text> <!-- 显示标题 -->
  <button bindtap="handleClick">点击我</button> <!-- 按钮点击事件 -->
</view>


my-component.wxss 文件

button {
  color: white; /* 字体颜色 */
  background-color: blue; /* 背景颜色 */
}


2. 在小程序的页面中引入组件

接下来,在你想使用这个组件的页面中,需要在该页面的 json 配置文件里使用 usingComponents 引入。

page.json 示例

{
  "usingComponents": {
    "my-component": "/path/to/my-component/my-component" // 指定组件的路径
  }
}


3. 使用组件

在页面的 wxml 文件中,使用我们刚刚创建的组件。

page.wxml 示例

<view>
  <my-component title="Hello World" bind:myevent="handleMyEvent"></my-component> <!-- 使用自定义组件 -->
</view>


4. 组件的数据传递与事件处理

最后,我们需要在页面的 js 文件中处理组件的事件和数据传递。

page.js示例

Page({
  data: {},
  handleMyEvent(e) {
    // 处理自定义组件触发的事件
    console.log(e.detail.message); // 输出来自组件的消息
  }
});

小结:通过以上步骤,我们成功地创建并使用了一个自定义组件。总结一下,使用 usingComponents 的流程主要包括以下几个环节:

 

创建自定义组件:在指定目录下创建 .js.wxml .wxss 文件,并编写相应的代码。

在小程序页面中引入组件:在页面的配置文件中使用 usingComponents 引入组件。

使用组件:在页面的 .wxml 文件中插入组件标签并设置属性。

处理数据和事件:在页面的 .js 文件中处理来自组件的事件。


博客评论
还没有人评论,赶紧抢个沙发~
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。