簡體   English   中英

重新加載后Vuex狀態為空

[英]Vuex state empty after reload

在一個突變中,我正在改變我的state如:

try {
  const response = await axios.put('http://localhost:3000/api/mobile/v3/expense/vouchers/form_refresh', sendForm, {
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      Authorization: 'Bearer ###'
    }
  });

  var obj = cloneDeep(response.data);
  var temp = cloneDeep(response.data.line_items_attributes.nested_form)

  temp = Object.keys(temp).map(key => {
    return {
      ...temp[key]
    }
  });

  obj.line_items_attributes.nested_form = cloneDeep(temp);

  state.form = cloneDeep(obj);
  console.log(state.form);
} catch (error) {
  ...
}

因此, state應保存一個以對象為條目的數組。 檢查state也顯示相同。 它顯示在視圖上。 現在重新加載時,除了數組內的對象外,所有內容都保留在state內。 它只是在商店內顯示一個空數組:

line_items_attributes:
  attribute: "line_items_attributes"
  label: "Positionen"
  model_class: "expense_line_item"
  nested_form: []              // <---- Object is gone

Nested_form 是后端下發的hahsmap。 我只是把它變成一個數組。 line_items_attribute 是存儲在狀態中的對象的屬性。 編輯:但如果沒有轉換,它也無法工作。 那里分配的狀態沒有得到保留。

商店.js

const store = createStore({
    strict: false,
    plugins: [createPersistedState()],
    modules: {
        expense,
        invoice
    }
});

調用動作/突變,如:

const updateOuter = (event, refreshable, propertyName) => {
   store.dispatch('expense/updateOuterValue', ({
      refresh: refreshable,
      propertyName: propertyName,
      value: event.target.checked ? 1 : 0
   }))
};

編輯:

在調用突變后更改不同的值時,重載后將保留nested_form對象。

如果我兩次調用突變似乎有效......知道這是怎么回事嗎?

問題是在突變中執行 axios。 必須有一個Vuex突變內部沒有異步調用。 正如@e200 所建議的

您不應該在突變內部執行異步操作,而應使用操作。

因此,這不僅僅是最佳實踐,而是必須做的。 在這里解釋: 突變必須是同步的

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM