入坑uni-app受不了自有组件极差的体验便自己写了个switch组件
uni-app坑不少,修改switch组件的原有样式在浏览器上能正常显示,但到了打包成APP后却不起作用;使用提供的方法style="transform:scale()只能按比例缩放,可定制性太差!这才打起自己写组件的念头,源码如下:
<template> <view> <view class="weui-switch" :class="{'weui-switch-on' : isChecked}" :value="value" @tap="toggle"></view> </view> </template> <script> export default { name: 'myswitch', props: { value: { type: Boolean, default: true } }, data () { return { isChecked: this.value } }, watch: { value (val) { this.isChecked = val }, isChecked(val) { this.$emit('change', val); } }, methods: { toggle() { this.isChecked = !this.isChecked; } } } </script> <style> .weui-switch { display: block; position: relative; width: 94rpx; height: 45rpx; outline: 0; border-radius: 30rpx; box-sizing: border-box; background-color: #DFDFDF; transition: background-color 0.1s, border 0.1s; cursor: pointer; } .weui-switch:before { content: " "; position: absolute; top: 0; left: 0; width: 94rpx; height: 45rpx; border-radius: 30rpx; background-color: #3D424F; transition: transform 0.35s cubic-bezier(0.45, 1, 0.4, 1); } .weui-switch:after { content: " "; position: absolute; top: 2rpx; left: 4rpx; width: 40rpx; height: 40rpx; border-radius: 50%; background-color: #FFFFFF; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4); transition: transform 0.35s cubic-bezier(0.4, 0.4, 0.25, 1.35); } .weui-switch-on { border-color: #6F6F6F; background-color: #00F8E9; } .weui-switch-on:before { border-color: #1AAD19; background-color: #00F8E9; } .weui-switch-on:after { transform: translateX(48rpx); } </style>
引入方法:通过绑定change事件监听组件的开关状态
<myswitch v-model="item.state" @change="mywitch(item)"></myswitch>