vue2.0中computed和watch之间的区别

151 阅读1分钟

vue2.0中computed和watch之间的区别

1.computed能完成的功能,watch都可以完成

2.函数里面涉及到异步操作(setTimeout,ajax等),只能用watch

3.computed中的计算的属性有缓存,可以复用

    <div id="root">
        姓:<input type="text" v-model:value="firstname">
        名:<input type="text" v-model:value="lastname">
        姓名: <input type="text" v-model:value="fullname">
    </div>
  <script>
        const vm = new Vue({
            el: "#root",
            data: {
                firstname: "邓",
                lastname: '紫琪',
                fullname: "邓紫棋2" //watch实现要准备好初始值

            },
            //用计算属性computed实现:fullname
             computed: {
              fullname: {
                    get() {
                        console.log(this)
                        console.log("get被调用了")
                        return this.firstname + this.lastname //邓紫棋
                    },
                    set(value) {
                        const arr = value.split('-')
                        this.firstname = arr[0]
                        this.lastname = arr[1]
                   }
               }
            },
            //用监视属性watch实现:fullname
            watch: {
                //姓的检测
                firstname(newValue, oldValue) {
                    this.fullname = newValue + this.lastname
                },
                //名的检测
                lastname(newValue, oldValue) {
                    this.fullname = this.firstname + newValue
               }
            },

            //给watch里面添加异步操作
            watch: {
                //姓的检测
                firstname(newValue, oldValue) {
                    setTimeout(() => {
                         console.log(this)
                        this.fullname = newValue + this.lastname
                    }, 1000);
                    setTimeout(()=>{
                        console.log(this)
                        this.fullname = newValue+oldValue
                    },2000)

                },
                //名的检测
                lastname(newValue, oldValue) {
                    setTimeout(() => {
                        this.fullname = this.firstname + newValue
                    }, 1000)
                }

            },
             //计算属性computed添加异步操作
             computed: {
                fullname() {
            //这块返回值会返回到setTimeout上,而fullname返回为undeined,
            // 所以有异步操作时不能用计算属性。要用watch
               setTimeout(() => {
              return this.firstname + this.lastname
             }, 2000)

            }
            },
        });
        console.log(vm)
         </script>