用Vue实现点击一个按钮,实现切换样式的效果

代码演示如下:(写的不好的地方,请见谅)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .yangshi1 {
            background-color: aqua;
            width: 100px;
            height: 100px;
        }
        
        .yangshi2 {
            background-color: rebeccapurple;
            width: 100px;
            height: 100px;
        }
    </style>
</head>

<body>
    <div id="div">
        <button @click="qiehuan">切换</button>//给一个点击事件
        <div v-bind:class="{ yangshi1: ys1 ,yangshi2: ys2}"></div>//这里是两个class,这里看不懂的话可以去看看Vue的官网的学习教程,有很详细的介绍
    </div>
    <script src="./js/vue.js"></script>
    <script>
        var dianji = new Vue({
            el: "#div",
            data: {
                ys1: true,
                ys2: false
            },//记得一定要用 “  , ”隔开,不然会报错的
            methods: {
    //方法
                qiehuan() {
                    //当点击第一次时,ys1从true变为false,Style样式yangshi1就会隐藏
                    //再点击第二次的时候由false,变为true,显示样式
                    this.ys1 = !this.ys1
                        //代码运行到下面,值为false的时候,取反,就会为true,Style样式yangshi2就会显示
                        //这里到第二次点击的时候,就由true变为false,隐藏样式
                    this.ys2 = !this.ys2   //这里 “  !” 是取反
                }
            }

        })
    </script>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/funing-z/p/11760855.html