【问题标题】:How to execute code after action finished in vue js?vue js中动作完成后如何执行代码?
【发布时间】:2020-05-04 12:47:09
【问题描述】:

vue js中动作完成后如何执行代码?这是我的登录操作

  login: async ({commit},loginDTO)=>{
         return  commit('login',loginDTO);
  }

我的登录突变是这样的:

login:(state, loginDTO)=>{

 axios.post(loginEndpoint.login, loginDTO)
  .then(resp => {
    if(resp.data.statusCode == 1) {
      state.user.userId = resp.data.userId;
      state.user.response = resp.data.responseText;
      localStorage.setItem("token", "token")
      state.isLogin = true;
      router.push({name: 'Systems'});

    }
    else{
      alert(66);
      state.user.response = resp.data.responseText;
      }
  })
  .catch(err => {

  })
}

我从这样的组件中调用它:

    methods:{
      ...mapActions(['login']),
      async login1(){

        const loginDTO = {
          Username : this.user.Username,
          Password: this.user.Password
        };
        await this.$store.dispatch('login',loginDTO);

        this.$toastr.s("Message", "");

      }
    }

现在我需要 toast 消息,但在操作完成后。 已更新。

【问题讨论】:

    标签: vue.js action toastr


    【解决方案1】:

    使用 async-await,等待异步操作完成并同步更改以提交,然后再显示 toast:

    // action
    login: async ({commit},loginDTO)=>{
      try {
        const { data } = await axios.post(loginEndpoint.login, loginDTO)
        commit('login', data.userId, data.responseText, true);
      } catch(error) {
        commit('login', null, error.message, false);
      }
    }
    
    // mutation
    login: (state, userId, response, isLogin) {
      state.user.userId = userId;
      state.user.response = response;
      state.isLogin = isLogin
    }
    
    methods:{
    ...mapActions(['login']),
        async login1(){
        const loginDTO = {
          Username : this.user.Username,
          Password: this.user.Password
        };
        await this.$store.dispatch('login',loginDTO);
        this.$toastr.s("Message", "");
      }
    }
    

    【讨论】:

    • 我试过了,没用,toast message在action完成之前执行
    • 这应该有效。你能用你在调度和创建事件时使用的实际代码更新你的问题吗?突变
    • 您错误地使用了动作和突变。您的应用程序逻辑和突变都发生在一个突变中,而它应该以一种非常抽象的方式发生在一个动作中。突变应该只是同步提交
    • 我用伪代码更新了我的答案,说明你的动作和突变应该是什么样子。在您对配置进行一些修改后,它应该可以工作
    【解决方案2】:

    我想你需要做的就是像往常一样在action完成后调用toast函数,ajax后回调函数返回200,比如我用了

    https://github.com/ankurk91/vue-toast-notification

    然后在回调中像这样运行它

    this.$toast.open('You did it!');

    (确保 toast 已在您的 vue 实例上注册)

    【讨论】:

    • 我想让动作异步并使用 await 调用它
    猜你喜欢
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 2012-02-08
    • 2014-10-27
    • 2022-01-10
    • 2022-11-01
    相关资源
    最近更新 更多