简体   繁体   English

VueX / VueJs:在异步过程之后执行组件中的代码

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

I'm trying to display a toast when a async request is finished. 我正在尝试在异步请求完成时显示祝酒词。 I've implemented this process: 我实现了这个过程:

  1. Single File Component calls updateUserProfile() actions in my VueX store 单个文件组件在我的VueX存储中调用updateUserProfile()操作
  2. updateUserProfile() actions makes a outgoing HTTP request on a server using Axios updateUserProfile()操作使用Axios在服务器上发出传出HTTP请求
  3. When succeeded, I use a mutation to update the user profile in my store and i would like to show a toast from my single file component. 成功后,我使用一个变体来更新商店中的用户个人资料,并且我想展示我的单个文件组件的祝酒词。

Problem is that the response object is always undefined in my component. 问题是响应对象在我的组件中始终是未定义的。 Where is my mistake ? 我的错误在哪里?

Error : 错误:

profile.vue?a62a:328 Uncaught (in promise) TypeError: Cannot read property 'data' of undefined at eval (profile.vue?a62a:328) profile.vue?a62a:328 Uncaught(in promise)TypeError:无法读取eval中未定义的属性'data'(profile.vue?a62a:328)

Store: 商店:

/*
  * 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);
  });

}

Component: 零件:

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.");
            }
        });
    }
}

Well, 好,

It would be better idea if You trigger the toast from the Vuex store itself as mentioned below. 如果您按照以下所述从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);
   });
},

and inside mutation you can have a general notification toast and you can pass type, message and title as below. 在变体内部,您可以有一个常规的通知toast并且可以按如下所示传递类型,消息和标题。

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

NOTE: Do not forget to load toast element at the root level in order to display in the UI. 注意:不要忘记在根级别加载toast元素以便在UI中显示。

Here is working example 这是工作示例

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM