Vue data与computed的区别


区别

  1. data中的属性并不会随赋值变量的改动而改动
  2. computed属性属于持续变化跟踪。在computed属性定义的时候,这个computed属性就与给它赋值的变量绑定了。改变这个赋值变量,computed属性值会随之改变
错误使用场景
  
{{name}}
data() { return { name: this.$store.state.Detail.detailInfo, }; }, mounted() { this.$store.dispatch('getDetail',11); }, /*********************** this.$store.state.Detail.detailInfo的初始值为{}, 经过dispatch('getDetail',11) this.$store.state.Detail.detailInfo的值改变了 但name的值不变=>data中的属性并不会随赋值变量的改动而改动 ***********************/ 正确使用场景
{{name}}
computed:{ name(){ return this.$store.state.Detail.detailInfo } }, mounted() { this.$store.dispatch('getDetail',11); },

data中不能使用computed中的数据, computed中可以使用data数据

原理:
Vue 把数据抽象成了两层,第一层就是简单的数据(data),第二层就是 computed (依赖于 data,也就是依赖于前一层)。第二层可以引用第一层的数据,而第一层却不能引用第二层的数据。

其实归根结底就是一个 Vue 实例在渲染的时候数据解析的顺序问题,结论是:
props->methods->data->computed->watch->created。

官网的源码也写的很清楚,见下图

computed中可以使用data数据

使用data中的数据, 但是注意 只能用, 不能改!

data() {
   return {
       options: [{a: 1}]
   }
}
computed {
   // 写法一: 函数写法
   objArr() { this.options;  ...    return XXX}
   
   // 写法二: 完整对象写法
   objArr: {
       get() {
   		this.options;
           return XXX
       }
   }
}

需要改, 用computed完整形式, setter函数 能改!
computed 就是个变量, 有值get(){return}, 可以赋值set(newValue)

computed {
    objArr: {
		//返回objArr的值
        get() { return this.options;},  
		//对objArr赋值{b: 2}
        set(newValue) {
            //修改data值
            this.options.push(newValue);
        }
    }
}
// 2. 触发set函数 即给objArr赋值:
// 这里我们封装个方法:
methods: {
    setObjArr() {
        this.objArr = {b: 2}
    }
}
// 通过按钮点击触发

methods里使用和修改data, computed

直接改 this.options

相关