首页 > 解决方案 > vue js中动作完成后如何执行代码?

问题描述

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", "");

      }
    }

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

标签: vue.jsactiontoastr

解决方案


在展示 toast 之前,使用 async-await 并等待异步操作完成并同步更改以提交:

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

推荐阅读