vue 首页提示 | 根据vue路由跳转提示不同的消息
2018年11月15日1.创建home提示页面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<template> <div> <Message :show.sync="msgShow" :type="msgType" :msg="msg"/> </div> </template> <script> export default { name: 'Home', data() { return { msg : '', //消息 msgType : '', //消息类型 msgShow : false //是否显示消息,默认不显示 } }, beforeRouteEnter(to, from, next) { //组件内的路由导航守卫 const fromName = from.name //路由的名称,对应路由配置中的 name next(vm => { //确认导航 if (vm.$store.state.auth) { //通过 vm 参数访问组件实例,已登录时,评估路由名称 switch (fromName) { case 'Register': //如果从注册页面跳转过来 vm.showMsg('注册成功') //显示注册成功 break } } }) }, methods: { showMsg(msg, type = 'success') { this.msg = msg this.msgType = type this.msgShow = true } } } </script> <style scoped> </style> |
2.编辑路由文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
import Vue from 'vue' //引入vue import Router from 'vue-router' //引入路由组件 Vue.use(Router) //vue使用router组件 /** * 路由配置的地方 * @type {*[]} */ const routes = [ { path: '/auth/register', name: 'Register', component: () => import('@/views/auth/Register') }, // 首页路由配置 { path: '/', name: 'Home', component: () => import('@/views/Home') }, // 其他未配置的路由都跳转到首页 { path: '*', // 重定向 redirect: '/' } ] /** * 新建一个路由 * @type {VueRouter} */ const router = new Router({ mode: 'history', routes }) /** * 全局前置守卫 */ router.beforeEach((to, from, next) => { const auth = router.app.$options.store.state.auth //获取仓库里的登录信息 if (auth && to.path.indexOf('/auth/') !== -1) { //如果当前用户已登录,且目标路由包含 /auth/ ,就跳转到首页 next('/') } else { next() } }) /** * 设置出口和返回的数据 */ export default router |
效果