vue自定义开关组件使用详解

Lark ·
更新时间:2024-09-20
· 48 次阅读

本文实例为大家分享了vue自定义开关组件的具体代码,供大家参考,具体内容如下

switch.vue:

<template>   <div class="disLB">     <div class="switch disLB" @click="toggleSwitch" :class="isOpen?'switch-on':''">       <span class="disB switch-circle" :class="isOpen?'on':''"></span>     </div>   </div> </template> <script> export default {   data() {     return {       // isOpen: false     }   },   props: ["isOpen"],   methods: {     toggleSwitch() {       // 子组件不能直接修改父组件的数据,要通过$emit       this.$emit('changeSwitch')     }   } } </script> <style lang="less" scoped>   .switch {     position: relative;     border-radius: 20px;     border: 1px solid #dfdfdf;     width: 45px;     height: 23px;     .switch-circle {       position: absolute;       width: 21px;       height: 21px;       background-color: #fff;       border-radius: 50%;       border: 1px solid #dfdfdf;       box-shadow: 0 1px 1px #ccc;     }     .on {       right: 0;       // background-color: #64bd63;       border-color: #64bd63;       transform: translate(X);       transition: transform 0.5s, right 0.5s;     }   }   .switch-on {     background-color: #64bd63;   } </style>

在父组件中引入并传值使用:

<template>     <toggle-switch :isOpen="systemConfig.enable_email" @changeSwitch="changeSwitch" v-model="systemConfig.enable_email"></toggle-switch> </template> <script> import toggleSwitch from '../../components/switch.vue'; export default {     data() {         return {}     },     components: {         toggleSwitch     },     methods: {         changeSwitch() {           this.systemConfig.enable_email = !this.systemConfig.enable_email;         }     } }

效果图:

注:

父组件向子组件传值,可以直接通过:isOpen="systemConfig.enable_email"传递数据,子组件通过 prop 接收数据:props: ["isOpen"],
但子组件不能直接修改父组件的数据,可以通过 $emit 调用父组件的方法来修改父组件的数据,$emit 的第一个参数要与父组件 @ 后的名称保持一致。



VUE 开关

需要 登录 后方可回复, 如果你还没有账号请 注册新账号