Skip to main content

小程序写法对照指南

一、状态值

// index.wxml
<view>
<text>{{ count }}</text>
<button bindtap="handleAdd">+1</button>
</view>

// index.js
Component({
data: {
count: 0,
},
methods: {
handleAdd() {
this.setData({
count: this.data.count + 1,
});
},
},
});

二、显示隐藏

<view>
<i-button wx:if="{{show}}">按钮</i-button>

<i-button wx:if="{{show}}">显示</i-button>
<i-button wx:else>隐藏</i-button>
</view>

三、属性传值

<i-button type="primary">按钮</i-button>
<i-button disabled>按钮</i-button>
<i-button loading="{{true}}">按钮</i-button>
<i-button name="{{getName()}}">按钮</i-button>
<i-button bindtap="handleAdd">按钮</i-button>

四、类名 & 样式

<view
class="i-button i-button--type-{{type}}"
>
按钮
</view>
<view
style="width: 300rpx; font-size: 16px;"
>
按钮
</view>

五、插槽

1、默认插槽

// index.wxml
<view>
<slot />
</view>

2、具名插槽

2-1、定义

注意 :::

在微信小程序中,由于 WXML 语法的限制,<slot> 必须写成 <slot></slot>,不能写成 <slot />

// /components/i-button/i-button.wxml
<view>
<slot name="prefixContent"></slot>
<slot></slot>
<slot name="suffixContent"></slot>
</view>

// /components/i-button/i-button.js
Component({
options: {
multipleSlots: true // 启用多插槽支持
},
properties: {
// 组件的属性
},
data: {
// 组件的初始数据
},
methods: {
// 组件的方法
}
});

// /components/i-button/i-button.json
{
"component": true
}

2-2、使用

// index.wxml
<view>
<i-button>
<view slot="prefixContent">
搜索
</view>
按钮
<view slot="suffixContent">
<i-icon name="Search"></i-icon>
</view>
</i-button>
</view>

// index.json
{
"usingComponents": {
"i-button": "/components/i-button/i-button",
"i-icon": "/components/i-icon/i-icon"
}
}

六、Props

// i-button.wxml
<button
class="i-button i-button--size-{{size}} {{className}}"
style="{{style}}"
disabled="{{disabled}}"
>
<slot></slot>
</button>

// i-button.js
Component({
externalClasses: ['className'],
properties: {
// 是否禁用
disabled: {
type: Boolean,
value: false
},
// 按钮尺寸
size: {
type: String,
value: 'medium',
options: ['small', 'medium', 'large']
},
// 自定义样式
style: {
type: String,
value: ''
}
}
})

// i-button.json
{
"component": true,
"usingComponents": {}
}

// 使用
<view>
<i-button
size="large"
disabled="{{false}}"
className="custom-class"
style="color: red;"
>
按钮文字
</i-button>
</view>

七、Emit

// button.wxml
<button
class="i-button i-button--size-{{size}} custom-class"
style="{{customStyle}}"
bindtap="handleClick"
disabled="{{disabled}}"
>
<slot></slot>
</button>

// button.js
Component({
externalClasses: ['custom-class'],
properties: {
disabled: {
type: Boolean,
value: false,
},
size: {
type: String,
value: 'medium',
},
customStyle: {
type: String,
value: '',
},
},

methods: {
handleClick(e) {
this.triggerEvent('click', e);
},
},
});

// button.json
{
"component": true,
"usingComponents": {}
}

// 使用
<view class="container">
<i-button
custom-class="my-custom-class"
size="large"
bind:click="handleButtonClick"
>
点击我
</i-button>
</view>