【问题标题】:VueJS - VueX : displaying notification after async processVueJS - VueX:异步进程后显示通知
【发布时间】:2019-07-28 05:38:26
【问题描述】:

我的单个文件组件的提取:

<script>
import { mapGetters, mapActions } from 'vuex';

export default {
    data () {
        return {
            firstname: this.$store.getters.user.firstName,
            lastname: this.$store.getters.user.lastName,
        }
    },
    methods: {
        ...mapActions([
            'updateUserProfile'
        ]),
        // Function called when user click on the "Save changes" btn
        onSubmit () {
            console.log('Component(Profile)::onSaveChanges() - called');
            const userData = {
                firstName: this.firstname,
                lastName: this.lastname
            }
            this.updateUserProfile(userData);
        }
    }
}
</script>

在我的 VueX 商店中:

我已经管理了一个 LOADING 状态,用于显示加载微调器。

现在,我想使用 toastr 库以编程方式显示通知小部件:toastr.success("Your profile has been updated");

我应该把这段代码放在哪里?我认为将此代码直接放在商店的 updateUserProfile 函数上并不是一个好习惯,而是更多地放在进行调用的单个文件组件上?

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

    if (!state.jwtToken) {
      return
    }

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

      // Store user data in local storage
      localStorage.setItem('user', JSON.stringify(res.data.data));

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

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

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

  }

【问题讨论】:

    标签: vue.js vuejs2 vuex


    【解决方案1】:

    您可能应该从您的操作中返回承诺:

    /*
    * Action used to fetch user data from backend
    */
    updateUserProfile ({commit, state}, userData) {
    
        if (!state.jwtToken) {
          throw new Error('unauthenticated')
        }
    
        // Inform VueX that we are currently loading something. Loading spinner will be displayed.
        commit('SET_IS_LOADING', true);
    
        return axiosBackend.put('/user/profile', userData, { headers: { Authorization: state.authString } } ).then(res => {
    
          console.log('PUT /user/profile', res);
    
          // Store user data in local storage
          localStorage.setItem('user', JSON.stringify(res.data.data));
    
          // 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.data
        })
        .catch(error => {
          // Reset isLoading
          commit('SET_IS_LOADING', false);
          throw error
        });
    }
    

    然后在你的组件中使用这个承诺:

    onSubmit () {
        console.log('Component(Profile)::onSaveChanges() - called');
        const userData = {
            firstName: this.firstname,
            lastName: this.lastname
        }
        this.updateUserProfile(userData).then(user => {
            toastr.success("Your profile has been updated")
        }).catch(error => {
            toastr.error("Something bad happened")
        })
    }
    

    【讨论】:

      【解决方案2】:

      你可以从 action 中返回一个 Promise

      updateUserProfile ({commit, state}, userData) {
      
        if (!state.jwtToken) {
          return
        }
      
        // Inform VueX that we are currently loading something. Loading spinner will be displayed.
        commit('SET_IS_LOADING', true);
      
        return axiosBackend.put('/user/profile', userData, { headers: { Authorization: state.authString } } ).then(res => {
      
          console.log('PUT /user/profile', res);
      
          // Store user data in local storage
          localStorage.setItem('user', JSON.stringify(res.data.data));
      
          // 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.data
        })
        .catch(error => {
          // Reset isLoading
          commit('SET_IS_LOADING', false);
          throw error
        });
      }
      

      然后在 Vue 组件中:

        onSubmit () {
          console.log('Component(Profile)::onSaveChanges() - called');
          const userData = {
              firstName: this.firstname,
              lastName: this.lastname
          }
          this.updateUserProfile(userData)
            .then(data => {
              toastr.success("Your profile has been updated");
            })
            .catch(error => {
              console.error(error)
            })
      }
      

      【讨论】:

        猜你喜欢
        • 2018-08-07
        • 2019-09-14
        • 1970-01-01
        • 2020-08-09
        • 1970-01-01
        • 2020-07-24
        • 1970-01-01
        • 2021-04-23
        • 2017-03-17
        相关资源
        最近更新 更多