做一個個性化的switch切換按鈕
阿新 • • 發佈:2018-11-08
需求背景:公司有個微信小程式專案,需要用到大量獨特的切換按鈕,類似開關這種按鈕,微信小程式自帶的switch是不能填寫文字的,所以直接,而且微信小程式使用的框架是基於vue的mpvue,mpvue出來的時間也短,估計很少這種輪子,所以就只能自己手擼一個,因為是微信小程式所以畫素單位是rpx,如果是普通vue專案也可以直接用這個元件,修改畫素單位即可單位
<template> <div id="myswitchBox" @click="handleClick" :style="bg"> <span :class="{swText:isTrues,swTexts:isTrue}" :style="inOutText">{{valueText}}</span> <i :class="{circle:isTrues,circles:isTrue}"></i> </div> </template> <script> export default{ props: ["mode"], data () { return { isTrue:false, isTrues:true } }, computed: { bg(){ if(this.mode=="是否"||this.mode=="一般嚴重"||this.mode=="有無"){ if(this.isTrues){ return "background: #cccccc;" }else{ return "background: #F168A8;" } }else if(this.mode=="內牆外牆"){ if(this.isTrues){ return "background: #648FF3" }else{ return "background: #F168A8;" } } }, inOutText(){ if(this.mode=="內牆外牆"||this.mode=="一般嚴重"){ if(this.valueText=="內牆"||this.valueText=="一般"){ return "transform:translate(12px,0)" }else{ return "transform:translate(-12px,0)" } }else{ return "" } }, valueText(){ if(this.mode=="是否"){ if(this.isTrue){ return "是" }else{ return "否" } }else if(this.mode=="內牆外牆"){ if(this.isTrue){ return "外牆" }else{ return "內牆" } }else if(this.mode=="一般嚴重"){ if(this.isTrue){ return "嚴重" }else{ return "一般" } }else if(this.mode=="有無"){ if(this.isTrue){ return "有" }else{ return "無" } } } }, methods: { handleClick(){ if(this.isTrue){ this.isTrue = false; this.isTrues = true; this.$emit("myClick",this.valueText); }else{ this.isTrue = true; this.isTrues = false; this.$emit("myClick",this.valueText); } } } } </script> <style scoped> #myswitchBox{ width: 120px; height: 50px; line-height: 50px; border-radius: 25px; position: relative; display: flex; align-items: center; } #myswitchBox .circle{ width: 46px; height: 46px; border-radius: 50%; background: white; position: absolute; left: 0; top: 2px; } #myswitchBox .circles{ width: 46px; height: 46px; border-radius: 50%; background: white; position: absolute; right: 0; top: 2px; } #myswitchBox .swText{ display: inline-block; position: absolute; right: 28px; color: white; } #myswitchBox .swTexts{ display: inline-block; position: absolute; left: 28px; color: white; } </style>
註釋:這是一個單獨的vue元件,可以直接引入使用,可以傳入mode引數,可以自己修改,