Home > Mobile >  How to trigger a function on route-change from a specific route?
How to trigger a function on route-change from a specific route?

Time:01-04

I have login component which has the following method:

  login() {
    this.$v.loginValidationGroup.$touch();
    if (this.$v.loginValidationGroup.$error) {
      return;
    }
    this.setLogsInfo();

    userService.login(this.email, this.password, this.twoFactorAuthCode, this.rememberMe, this.userOs, this.userIp, this.userAgent, this.browserName)
      .then(authenticationToken => {
        if(authenticationToken === "2FactorAuthRequired") {
          this.is2FAuthEnabled = true;
        }
        else {
          this.$store.dispatch('login', authenticationToken);
          this.$router.push('/Home');
        }
      })
      .catch(error => {
        if (error instanceof AuthenticationError && error.errorType === AuthErrorType.WRONG_CREDENTIALS) {
          this.loginError = 'wrongLoginCredentials';
        } else if (error instanceof ValidationError) {
          this.loginError = 'invalidLoginCredentials';
        } else {
          this.loginError = 'unknownLoginError';
        }
        this.$v.$reset();
      });
  },

After login the user is redirected to the Home component.

On my Home component I have made a modal that contains a welcome message:

   <template>
    <div visible">
      <div  role="document">
        <div >
          <div >
            <h5  id="exampleModalLabel">Welcome</h5>
          </div>
          <div >
            some text....
          </div>
        </div>
      </div>
    </div>
   </template>

Is there any way I can tell the application to set the v-model "visible" to true when routing from the Login component to the Home component? Mind you I ONLY want the v-model be set to true when entering the page from the Login compoment,not any other component.

CodePudding user response:

Basically, you can make use of in-component navigation guard called "beforeRouteEnter". In it, you have access to the route which the router navigated from. You check if the from route is the login route, then set the visible variable through vm component instance provided by next function (remember in this navigation guard you don't have access to this component instance)

Home component:

  data(){
    return {
      visible: false
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (from.path === "/login") {
        vm.visible = true;
      }
    });
  },

CodePudding user response:

In your Home.vue component, you can set a router watcher which would have to and from params to check the previous and current routes.

Here is an example-

Home.vue

watch: {
  $route(to, from) {
    if(from.name == "Login") {
      this.visible = true;
    }
  }
}
  • Related