computed vs watch / computed 和watch使用规则

官方文档 计算属性和监听器

案例

new Vue({
            el: '#app',
            data() {
                return {
                    title: 'hello word',
                    firstName:'四',
                    lastName:'李',
                    people:{
                        name:'xx',
                        age:18,
                        hobby:'k 歌'
                    }
                }
            },
            // 一个值由其他值组合得到,这些值的变化了我也跟着变,适合做多个值影响一个值的情绪
            computed: {
                fullName() {
                    return this.firstName+this.lastName
                }
            },
            // 一个值变化了,我要做些事情,适合做一个值影响多个值的情形
            watch: {
                people: {
                    immediate: true, // 首次加载立即执行
                    deep: true, // 深度监听,多用于深层嵌套的对象
                    handler(newValue, oldValue) {
                        // do some sth
                    }
                },
                firstName (newValue, oldValue) {
                    this.fullName = val + ' ' + this.lastName
                },
                lastName (newValue, oldValue) {
                    this.fullName = this.firstName + ' ' + val
                }
            },
        })

使用规则

watch 多用于 一对多,一个值的变化影响多个值
computed多用于多对 一,多个值的变化影响一个值

你可能感兴趣的:(computed vs watch / computed 和watch使用规则)