用vue实现一个开关按钮

css样式

<style>
        *{
            margin: 0;
            padding: 0;
        }
        .app{
            background-color: red;
            width: 100px;
            height: 36px;
            border-radius: 18px;
            overflow: hidden;
            transition: all 1s;
        }
        .app>div{
            background-color: #fff;
            width: 34px;
            height: 34px;
            border-radius: 50%;
            transition: all 1s;
            margin: 1px;
        }
        .active1{
            background-color: green;
        }
        .active{
            transform: translateX(64px);
        }
    </style>

html

        <div class="wrapper">
            <div class="app" :class="sum==true? 'active1':'' " @click="demo()">
                <div :class="sum==true? 'active':''"></div>
            </div>
            <span>状态:{{msg}}</span>
        </div>

javascript

<script src="../js/vue.js"></script>
    <script>
        const vm = new Vue({
            //挂载dom
            el:".wrapper",
            //数据
            data:{
                sum:false,
                msg: 'OFF'
            },
            methods: {
                demo(sum){
                    if(this.sum==false){
                    this.sum=true
                    this.msg='ON'
                   }else{
                    this.sum=false
                    this.msg='OFF'
                   }
                }
            },
            
        })

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue.js一个流行的JavaScript框架,用于构建用户界面。在Vue中创建跷跷板开关按钮可以通过使用组件和条件渲染来实现。 首先,创建一个Vue组件来表示跷跷板开关按钮。在组件中,你可以使用`data`选项来定义按钮的状态。例如,你可以使用一个布尔值来表示按钮开关状态。 ```html <template> <button @click="toggleSwitch" :class="{ 'on': isOn, 'off': !isOn }"> <span>{{ isOn ? 'ON' : 'OFF' }}</span> </button> </template> <script> export default { data() { return { isOn: false, // 初始化按钮状态为关闭 }; }, methods: { toggleSwitch() { this.isOn = !this.isOn; // 切换按钮状态 }, }, }; </script> <style> button { width: 100px; height: 50px; } .on { background-color: green; } .off { background-color: red; } </style> ``` 在上面的示例中,我们创建了一个按钮组件,其中使用了Vue的条件渲染和事件绑定。通过点击按钮,`toggleSwitch`方法会被调用,从而切换按钮的状态。 在组件的模板中,我们使用了动态类绑定`:class`来根据按钮状态来设置不同的样式。当按钮状态为开启时,添加`on`类,当按钮状态为关闭时,添加`off`类。 这样,你就可以在Vue应用中使用这个跷跷板开关按钮组件了。只需在父组件中引入该组件,并将其添加到模板中的适当位置。 ```html <template> <div> <h1>跷跷板开关按钮示例</h1> <switch-button></switch-button> </div> </template> <script> import SwitchButton from './SwitchButton.vue'; export default { components: { SwitchButton, }, }; </script> ``` 这样,你就可以看到一个可以切换状态的跷跷板开关按钮了!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值