Skip to content

Instantly share code, notes, and snippets.

@hrs-nkym
Created February 13, 2019 16:55
Show Gist options
  • Save hrs-nkym/485386a4a3881299520653697be508c6 to your computer and use it in GitHub Desktop.
Save hrs-nkym/485386a4a3881299520653697be508c6 to your computer and use it in GitHub Desktop.
vue-router-test
<div id="app">
<p>
<router-link to="/about">About</router-link>
<router-link to="/dashboard">Dashboard</router-link>
</p>
<router-view></router-view>
</div>
var About = { template: '<h1>About</h1>' };
var Dashboard = { template: '<div><h1>Dashboard</h1><router-link to="/logout">Logout</router-link></div>' };
var Auth = {
loggedIn: false,
login: function() { this.loggedIn = true },
logout: function() { this.loggedIn = false }
}
var Login = {
template: '<input type="submit" value="Login" v-on:click="login">',
methods: {
login: function() {
Auth.login();
router.push(this.$route.query.redirect);
}
}
};
var Logout = {
template: '<input type="submit" value="Logout" v-on:click="logout">',
methods: {
logout: function() {
Auth.logout();
router.push('/');
}
}
}
var routes = [
{ path: '/about', component: About },
{ path: '/dashboard', component: Dashboard, meta: { requiresAuth: true } },
{ path: '/login', component: Login },
{ path: '/logout', component: Logout },
];
var router = new VueRouter({
routes
});
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth) && !Auth.loggedIn) {
next({ path: '/login', query: { redirect: to.fullPath }});
} else {
next();
}
});
var app = new Vue({
el: '#app',
// components: {
// 'About': About
// },
router
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.4/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.2/vue-router.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment