欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

动态绑定的两种方式

程序员文章站 2024-03-23 23:24:52
...

第一种:属性绑定
第二种:计算属性绑定

区别:计算属性是确定发生变化后才进行更新·
其实知识点还是之前总结的,没有新知识点,直接上代码吧!

<!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">
    <style>
        span {
            background: red;
            display: inline-block;
            padding: 10px;
            color: #fff;
            margin: 10px 0;
        }

        .changeColor span {
            background: green;
        }

        .changeLength span:after {
            content: '米萊迪';
            margin-left: 10px;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <title>Vue CDN</title>
</head>

<body>
    <div id="vue-app">
        <h1>动态绑定样式 两种方式</h1>
        <!-- <h2>示例1 属性绑定</h2>
        <div @click="mrChangeColor = !mrChangeColor" v-bind:class="{changeColor:mrChangeColor}">
            <span>Hello</span>
        </div> -->
        <h2>示例2 计算属性绑定</h2>
        <button @click="mrChangeColor = !mrChangeColor">ChangeColor</button>
        <button @click="mrChangeLength = !mrChangeLength">ChangeLength</button>
        <div v-bind:class="compClasses">
            <span>Hello</span>
        </div>
        <!-- 计算属性是确定发生变化后才进行更新 -->
</body>
<script>
    new Vue({
        el: '#vue-app',
        data() {
            return {
                mrChangeColor: true,
                mrChangeLength: false,

            };
        },
        methods: {},
        computed: {
            compClasses() {
                return {
                    changeColor: this.mrChangeColor,
                    changeLength: this.mrChangeLength,
                };
            }
        }
    });
</script>

</html>