vuex的坑

引言

嗚嗚嗚坑死我了

Object.assign

Object.assign reads the value of the property from the source object, it doesn’t copy getters/setters
來自stackOverflow
Object.assign 方法只會拷貝源對象自身的並且可枚舉的屬性到目標對象。該方法使用源對象的[[Get]]和目標對象的[[Set]],所以它會調用相關 getter 和 setter。

var a={
    sub:{}
  };
  var b={
    sub:3
  };
  var initSub={};
  Object.defineProperty(a,'sub',{
    get(){
      console.log("觸發了a的getter");
      return initSub;
    },
    set(newValue){
      console.log('觸發了a的settter');
      initSub=newValue;
    }
  })
  Object.defineProperty(b,'sub',{
    get(){
      console.log("觸發了b的getter");
      return initSub;
    },
    set(newValue){
      console.log('觸發了b的settter');
      initSub=newValue;
    }
  })
  Object.assign(a,b);//觸發了b的getter   觸發了a的settter

遵循vue的響應式

Vuex中的store是響應式的,因此當要在對象上添加新屬性時,應該使用Vue.set()方法來監聽,否則state的狀態無法實現自動更新。

Vue.set(obj, 'newProp', 123)  

爲了避免這樣的情況出現,最好在store中提前初始化好所有需要使用的屬性。
注:如果我們要使用Object.assign的話,最好是已有的屬性之間變化,才能被watch檢測出來!

儘量避免直接在state上面進行操作

不要再上面進行遍歷操作

compute引入之後,最好不要直接用這個變量進行遍歷

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章