- 创建组件:在微信小程序的项目目录中,新建一个名为
components
的文件夹,然后在该文件夹下创建一个组件文件夹,例如my-component
。在my-component
文件夹中,创建一个my-component.wxml
文件,用于编写组件的模板;创建一个my-component.js
文件,用于编写组件的逻辑;创建一个my-component.wxss
文件,用于编写组件的样式。 - 编写组件模板:在
my-component.wxml
文件中,编写组件的模板结构。
<view class="my-component">
<text>{{message}}</text>
<button bindtap="handleClick">点击我</button>
</view>
- 编写组件逻辑:在
my-component.js
文件中,编写组件的逻辑代码。
Component({
properties: {
message: {
type: String,
value: 'Hello, World!'
}
},
methods: {
handleClick: function () {
console.log('按钮被点击');
}
}
});
在上述代码中,我们使用Component()
函数来创建一个组件,通过properties
属性定义组件的属性,通过methods
属性定义组件的方法。
- 编写组件样式:在
my-component.wxss
文件中,编写组件的样式。
.my-component {
background-color: #f2f2f2;
padding: 10px;
}
- 在页面中使用组件:在需要使用组件的页面的
json
文件中,引入组件。
{
"usingComponents": {
"my-component": "/components/my-component/my-component"
}
}
然后在页面的wxml
文件中,使用my-component
标签来引入和使用组件。
<my-component message="Hello, Uni-app"></my-component>
之前都是个人记录组件的常见和使用,有不足之处可以指出!