簡體   English   中英

VueX / VueJs:在異步過程之后執行組件中的代碼

[英]VueX/VueJs : Execute code in component after async process

我正在嘗試在異步請求完成時顯示祝酒詞。 我實現了這個過程:

  1. 單個文件組件在我的VueX存儲中調用updateUserProfile()操作
  2. updateUserProfile()操作使用Axios在服務器上發出傳出HTTP請求
  3. 成功后,我使用一個變體來更新商店中的用戶個人資料,並且我想展示我的單個文件組件的祝酒詞。

問題是響應對象在我的組件中始終是未定義的。 我的錯誤在哪里?

錯誤:

profile.vue?a62a:328 Uncaught(in promise)TypeError:無法讀取eval中未定義的屬性'data'(profile.vue?a62a:328)

商店:

/*
  * Action used to fetch user data from backend
  */
updateUserProfile ({commit, state}, userData) {

  // Inform VueX that we are currently loading something. Loading spinner will be displayed.
  commit('SET_IS_LOADING', true);

  axiosBackend.put('/user/profile', userData, { headers: { Authorization: state.authString } } ).then(res => {

    console.log('PUT /user/profile', res);

    // Set user Data in VueX Auth store
    commit('SET_USER_DATA', {
      user: res.data.data
    });

    // Reset is Loading
    commit('SET_IS_LOADING', false);

    return res.data;

  })
  .catch(error => {
    // Reset isLoading
    commit('SET_IS_LOADING', false);
  });

}

零件:

methods: {
    // mix the getters into computed with object spread operator
    ...mapActions([
        'updateUserProfile'
    ]),
    // Function called when user click on the "Save changes" btn
    onSubmit () {
        console.log('Component(Profile)::onSaveChanges() - called');
        const userData = {
            firstName: this.firstname,
        }
        this.updateUserProfile(userData).then( (response) => {
            console.log('COMPONENT', response);
            if (response.data.status === 200) {
                toastr.success("Your profile has been successfully updated.");
            }
        });
    }
}

好,

如果您按照以下所述從Vuex商店本身觸發toast ,那將是一個更好的主意。

callAddToCart: ({ commit }, payload) => {
    axiosBackend.put('/user/profile', userData, { headers: { Authorization: 
       state.authString }}).then(response => {
       commit("setLoading", false, { root: true });
       payload.cartKey = response.key;
       commit("setNotification", {
           type: 'success',
           title: `title`,
       });
       commit("ADD_TO_CART", payload);
   });
},

在變體內部,您可以有一個常規的通知toast並且可以按如下所示傳遞類型,消息和標題。

setNotification(state, {type, message, title}) {
    state.flash = { 
       type,
       title, 
       message
    }
}

注意:不要忘記在根級別加載toast元素以便在UI中顯示。

這是工作示例

希望這可以幫助!

暫無
暫無

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

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