switch为开关选择器,切换开启或关闭状态。
创建switch组件
在pages/index目录下的hml文件中创建一个switch组件。
<!-- xxx.hml -->
<div class="container">
<switch checked="true"></switch>
</div>
/* xxx.css */
.container {
flex-direction: column;
background-color: #F1F3F5;
}
添加属性和方法
switch组件通过textoff和showtext属性设置文本选中和未选中时的状态。设置checked属性值为true(组件为打开状态)。添加change事件,当组件状态改变时触发,触发后执行switchChange函数获取组件当前状态(关闭/打开)。
<!-- xxx.hml -->
<div class="container">
<switch showtext="true" texton="open" textoff="close" checked="true" @change="switchChange"></switch>
</div>
/* xxx.css */
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
switch {
texton-color: #002aff;
textoff-color: silver;
text-padding: 20px;
font-size: 50px;
}
// xxx.js
import promptAction from '@ohos.promptAction';
export default {
switchChange(e){
if(e.checked){
promptAction.showToast({
message: "open"
});
}else{
promptAction.showToast({
message: "close"
});
}
}
}
说明
当showtext属性值设置为true时,texton和textoff设置的文本才会生效。