制作一个像手机一样的充电状态显示组件,电量可以通过外部参数控制显示。
//html <div id="app"> <battery :charge="charge"></battery> </div> //css .battery { display: inline-flex; flex-direction: column; align-items: center; justify-content: center; } .top { background: #000; width: 20px; height: 10px; border-radius: 10px 10px 0 0; margin-bottom: 2px; } .outer { width: 40px; border: 5px solid #000; height: 80px; border-radius: 10px; display: flex; flex-direction: column; } .inner { background: #f00; flex: 1; margin: 2px; border-radius: 5px; } .inner.hidden { visibility: hidden; } //js const Battery = { props: ['charge'], template: ` <div class="battery"> <div class="top"></div> <div class="outer"> <div v-for="n in 5" class="inner" :class="{ hidden: n <= 5 - charge }" ></div> </div> </div> ` } const vm = new Vue({ components: { Battery, }, data () { return { charge: 0 } } }) vm.$mount('#app') setInterval(() => { vm.charge = (vm.charge + 1) % 6 }, 500)
运行效果如下
转自:https://forum.vuejs.org/t/battery-charge-status-component/105590