Created
February 25, 2019 15:30
-
-
Save NickBolles/2fbeb3038da22a9725bae311030c1add to your computer and use it in GitHub Desktop.
Nuxt On Login mixin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, Vue } from "vue-property-decorator"; | |
const DEFAULT_REDIRECT = "home"; | |
type redirectFn = () => string; | |
// You can declare a mixin as the same style as components. | |
@Component | |
export default class OnLoginMixin extends Vue { | |
protected redirect?: string | redirectFn = DEFAULT_REDIRECT; | |
protected watchLogin?: boolean = true; | |
private $$cleanupLogin: () => void; | |
public fetch() { | |
this.checkLoggedIn(); | |
} | |
public mounted() { | |
this.checkLoggedIn(); | |
this.$$cleanupLogin = this.$auth.$storage.watchState( | |
"loggedIn", | |
this.checkLoggedIn.bind(this) | |
); | |
} | |
public beforeDestroy() { | |
this.$$cleanupLogin(); | |
} | |
protected checkLoggedIn(...args) { | |
if (this.$auth.loggedIn) { | |
if (typeof this.redirect === "function") { | |
this.redirect = this.redirect.call(this, args); | |
} | |
return this.$auth.redirect(typeof this.redirect === "string" ? this.redirect : DEFAULT_REDIRECT); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment