Vue入門基礎(computed 計算屬性)

computed.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-computed-events">
        <h1>computed 計算屬性</h1>

        <!--methods-->
        <button @click='a++'>add to a</button>
        <button @click='b++'>add to b</button>

        <p>A-{{a}}</p>
        <p>B-{{b}}</p>
        <!-- 若是方法放在vue的methods中 每次修改屬性 都會觸發全頁面的方法 
            能夠經過將方法放入computed中能夠避免 觸發其餘非改變相關屬性的方法 
            使用時  方法不能帶括號-->
        <p>Age + A = {{ addToA }}</p>
        <p>Age + B = {{ addToB }}</p>

    </div>

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

</html>

computed.jshtml

new Vue({
    el: '#vue-app-computed-events',
    data() {
        return {
            a: 0,
            b: 0,
            age: 27
        }
    },
    methods: {

    },
    computed: { //computerd裏的方法都須要return值
        addToA() {
            return this.a + this.age;
        },
        addToB() {
            return this.age + this.b;
        }
    }
});

頁面效果vue

相關文章
相關標籤/搜索