Vue入門基礎(動態綁定css)

bangdingcss.htmljavascript

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

<head>
    <meta charset="UTF-8">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <title>Insert title here</title>
</head>

<body>
    <div id="vue-app-bangdingcss">
        <h1>動態綁定樣式的兩種方式</h1>
        <h2>示例1 屬性綁定</h2>
        <!--changeColor默認爲false 經過click取反修改css-->
        <div v-bind:class='{changeColor:setColor}' v-on:click='setColor=!setColor'>
            <span>屬性綁定</span>
        </div>

        <h2>示例2 計算屬性綁定</h2>
        <!--經過修改屬性值 進而觸發方法來修改樣式-->
        <button @click='setColor=!setColor'>點擊改變顏色樣式</button>
        <button v-on:click='setLength=!setLength'>點擊改變長度樣式</button>
        <div v-bind:class='computedClass'>
            <span>計算屬性綁定</span>
        </div>
    </div>

</body>
<script src="bangdingcss.js">
</script>

<!-- 樣式-->
<style>
    span {
        background: red;
        display: inline-block;
        padding: 10px;
        color: #fff;
        margin: 10px 0;
    }

    .changeColor span {
        background: green;
    }

    .changeLength span::after {
        content: 'MMMMMMM';
        margin-left: 10ox;
    }
</style>

</html>

bangdingcss.jscss

new Vue({
    el: '#vue-app-bangdingcss',
    data() {
        return {
            setColor: false, //默認false
            setLength: false
        }
    },
    methods: {
    },
    computed: {
        //經過方法來觸發修改樣式  注意用this引用屬性
        computedClass() {
            return { changeColor: this.setColor, changeLength: this.setLength };
        }
    }
});

頁面效果html

相關文章
相關標籤/搜索