Vue基础04计算属性和侦听器

170 阅读1分钟

Vue基础04计算属性和侦听器

遇到了很复杂的计算表达式,通常用计算属性来实现;计算属性与侦听器的区别

1 计算属性和侦听器,统计课程数量

计算属性有缓存性,如果值没有发生变化页面不会重新渲染

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
</head>
<body>
    <div id="app">
        <h2>{{title}}</h2>

        <input v-model="course" v-on:keydown.enter="addCourse"> 
        <button @click="addCourse">新增</button>

        <div v-for="item in courses" :key="item">
            {{ item }}
        </div>

        <div>课程总数:{{this.courses.length}}门</div>
        <div>课程总数(计算属性):{{courseTotal}}</div>
        <div>课程总数(侦听器):{{courseTotal2}}</div>
    </div>

    <script src="../js/vue.js"></script>

    <script>
        const app = new Vue({
            el: '#app',
            data() {
                return {
                    title: '购物车',
                    courses: ['Java课程', 'Web课程'],
                    course: '',
                    selectedCourse: '',
                    courseTotal2: 0
                }
            },
            methods: {
                addCourse() {
                    if (this.course == '' || this.courses.indexOf(this.course) > -1) {
                        return
                    }
                    this.courses.push(this.course)
                    this.course = ''
                }
            },
            computed: {
                courseTotal() {
                    return this.courses.length + '门'
                }
            },
            watch: {
                // courses(newValue, oldValue) {
                //     this.courseTotal2 = newValue.length + '门'
                // }
                courses: {
                    immediate: true,
                    // deep: true,
                    handler(newValue, oldValue) {
                        this.courseTotal2 = newValue.length + '门'
                    }
                }
            },
        })
    </script>
</body>
</html>

2 计算属性和侦听器区别

计算属性,具有缓存性,使用简单

语境上来说有差异

  1. Watch,一个值变化了,我要做一些事情,适合影响多个值的情形,异步、开销很大的操作
  2. Computed,一个值由其他值得来的,这些值变了我也要变,适合多个值影响一个值的情形