Note06--路由

1. AJAX的缺点

这里写图片描述

2. AJAX的缺点是前端为什么需要路由的重要原因!
3. 深层次嵌套路由:页面的一部分内容变换
    a. 使用angularJS本身的路由实现比较困难,GitHub搜索AngularUI;https://angular-ui.github.io
    b. UIRoute3.js
var routerApp = angular.module('routerApp', ['ui.router']);
routerApp.config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/index');
    $stateProvider
        .state('index', {
            url: '/index',
            views: {
                '': {
                    templateUrl: 'tpls3/index.html'
                },
                'topbar@index': {
                    templateUrl: 'tpls3/topbar.html'
                },
                'main@index': {
                    templateUrl: 'tpls3/home.html'
                }
            }
        })
        .state('index.usermng', {
            url: '/usermng',
            views: {
                'main@index': {
                    templateUrl: 'tpls3/usermng.html',
                    controller: function($scope, $state) {
                        $scope.addUserType = function() {
                            $state.go("index.usermng.addusertype");
                        }
                    }
                }
            }
        })
        .state('index.usermng.highendusers', {
            url: '/highendusers',
            templateUrl: 'tpls3/highendusers.html'
        })
        .state('index.usermng.normalusers', {
            url: '/normalusers',
            templateUrl: 'tpls3/normalusers.html'
        })
        .state('index.usermng.lowusers', {
            url: '/lowusers',
            templateUrl: 'tpls3/lowusers.html'
        })
        .state('index.usermng.addusertype', {
            url: '/addusertype',
            templateUrl: 'tpls3/addusertypeform.html',
            controller: function($scope, $state) {
                $scope.backToPrevious = function() {
                    window.history.back();
                }
            }
        })
        .state('index.permission', {
            url: '/permission',
            views: {
                'main@index': {
                    template: '这里是权限管理'
                }
            }
        })
        .state('index.report', {
            url: '/report',
            views: {
                'main@index': {
                    template: '这里是报表管理'
                }
            }
        })
        .state('index.settings', {
            url: '/settings',
            views: {
                'main@index': {
                    template: '这里是系统设置'
                }
            }
        })
});
    c. UIRoute3.html
<!doctype html>
<html ng-app="routerApp">

<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/bootstrap-3.0.0/css/bootstrap.css">
    <link rel="stylesheet" href="css/index.css">
    <script src="js/angular-1.3.0.js"></script>
    <script src="js/angular-animate.js"></script>
    <script src="js/angular-ui-router.js"></script>
    <script src="UIRoute3.js"></script>
</head>

<body>
    <div ui-view></div>
</body>

</html>
    d. Tlps3/index.html
<div class="container">
  <div ui-view="topbar"></div>
    <div ui-view="main"></div>
</div>
    e. Topbar.html
<nav class="navbar navbar-inverse" role="navigation">
    <div class="navbar-header">
        <a class="navbar-brand" ui-sref="#">ui-router综合实例</a>
    </div>
    <ul class="nav navbar-nav">
        <li>
            <a ui-sref="index">首页</a>
        </li>
        <li>
            <a ui-sref="index.usermng">用户管理</a>
        </li>
        <li>
            <a ui-sref="index.permission">权限管理</a>
        </li>
        <li>
            <a ui-sref="index.report">报表管理</a>
        </li>
        <li>
            <a ui-sref="index.settings">系统设置</a>
        </li>
    </ul>
</nav>
    f. Home.html
<div class="jumbotron text-center">
  <h2>首页</h2>
    <p>
        首页的形式一般比较<span class="text-danger">灵活</span>,而且可能随时发生变化。
    </p>
</div>
    g. Addusertypeform.html
<h3>新增用户</h3>
<form class="form-horizontal" role="form">
    <div class="form-group">
        <label class="col-md-2 control-label">
            邮箱:
        </label>
        <div class="col-md-10">
            <input type="email" class="form-control" placeholder="推荐使用126邮箱">
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">
            密码:
        </label>
        <div class="col-md-10">
            <input type="password" class="form-control" placeholder="只能是数字、字母、下划线">
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <div class="checkbox">
                <label>
                    <input type="checkbox">自动登录
                </label>
            </div>
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <button class="btn btn-primary" ng-click="backToPrevious()">返回</button>
        </div>
    </div>
</form>
    h. Highendusers.html
<div class="row">
    <div class="col-md-12">
        <h3>高端用户列表</h3>
    </div>
</div>
<div class="row">
    <div class="col-md-12">
        <table class="table table-bordered table-hover table-condensed">
            <thead>
                <tr>
                    <th>序号</th>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>作品</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td rowspan="2">1</td>
                    <td>大漠穷秋</td>
                    <td>29</td>
                    <td>《用AngularJS开发下一代WEB应用》</td>
                </tr>
                <tr>
                    <td>大漠穷秋</td>
                    <td>29</td>
                    <td>《用AngularJS开发下一代WEB应用》</td>
                </tr>
                <tr>
                    <td>2</td>
                    <td>大漠穷秋</td>
                    <td>29</td>
                    <td>《Ext江湖》</td>
                </tr>
                <tr>
                    <td>3</td>
                    <td colspan="2">大漠穷秋</td>
                    <td>《ActionScript游戏设计基础(第二版)》</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
    i. Normalusers.html
<div class="alert alert-success" role="alert">
  <strong>Well done!</strong>You successfully read <a href="#" class="alert-link">this important alert message</a>.
</div>
<div class="alert alert-info" role="alert">
    <strong>Heads up!</strong>This <a href="#" class="alert-link">alert needs your attention</a>, but it's not super important.
</div>
<div class="alert alert-warning" role="alert">
    <strong>Warning!</strong>Better check yourself, you're <a href="#" class="alert-link">not looking too good</a>.
</div>
<div class="alert alert-danger" role="alert">
    <strong>Oh snap!</strong> <a href="#" class="alert-link">Change a few things up</a> and try submitting again.
</div>
    j. Lowusers.html
<div class="btn-toolbar" role="toolbar">
    <div class="btn-group">
        <button type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-align-left"></span>
        </button>
        <button type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-align-center"></span>
        </button>
        <button type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-align-right"></span>
        </button>
        <button type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-align-justify"></span>
        </button>
    </div>
</div>
<div class="btn-toolbar" role="toolbar">
    <button type="button" class="btn btn-default btn-lg">
        <span class="glyphicon glyphicon-star"></span>Star</button>
    <button type="button" class="btn btn-default">
        <span class="glyphicon glyphicon-star"></span>Star</button>
    <button type="button" class="btn btn-default btn-sm">
        <span class="glyphicon glyphicon-star"></span>Star</button>
    <button type="button" class="btn btn-default btn-xs">
        <span class="glyphicon glyphicon-star"></span>Star</button>
</div>
    k. Usermng.html
<div class="row">
    <div class="col-md-3">
        <div class="row">
            <div class="col-md-12">
                <div class="list-group">
                    <a ui-sref="#" class="list-group-item active">用户分类</a>
                    <a ui-sref="index.usermng.highendusers" class="list-group-item">高端用户</a>
                    <a ui-sref="index.usermng.normalusers" class="list-group-item">中端用户</a>
                    <a ui-sref="index.usermng.lowusers" class="list-group-item">低端用户</a>
                    <a ui-sref="#" class="list-group-item">黑名单</a>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <button class="btn btn-primary" ng-click="addUserType()">新增用户</button>
            </div>
        </div>
    </div>
    <div class="col-md-9">
        <div ui-view></div>
    </div>
</div>
4. 前端路由的基本原理

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
element-admin 是一个基于 Vue.js 和 Element UI 的后台管理系统框架,它支持动态路由配置。 动态路由是指在用户登录后,根据用户的权限动态生成路由。这样可以保证用户只能访问他有权限访问的页面,提高系统的安全性。 在 element-admin 中,动态路由是通过在路由配置文件中定义一个 routes 数组来实现的。该数组中的路由对象可以通过后台接口获取,然后根据用户的权限进行筛选和过滤。 具体实现步骤如下: 1. 在路由配置文件中定义一个 routes 数组,并将该数组赋值给 router 的 routes 属性。 ```javascript import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) export const constantRoutes = [ { path: '/', component: Layout, redirect: '/dashboard', children: [ { path: 'dashboard', component: () => import('@/views/dashboard/index'), name: 'Dashboard', meta: { title: 'Dashboard', icon: 'dashboard' } } ] }, { path: '/login', component: () => import('@/views/login/index'), hidden: true } ] const createRouter = () => new Router({ mode: 'history', // require service support scrollBehavior: () => ({ y: 0 }), routes: constantRoutes }) const router = createRouter() export function resetRouter() { const newRouter = createRouter() router.matcher = newRouter.matcher // reset router } export default router ``` 2. 在路由配置文件中定义一个 asyncRoutes 数组,用于存放动态路由。 ```javascript export const asyncRoutes = [ { path: '/permission', component: Layout, redirect: '/permission/index', alwaysShow: true, // will always show the root menu name: 'Permission', meta: { title: 'Permission', icon: 'lock', roles: ['admin', 'editor'] // you can set roles in root nav }, children: [ { path: 'index', component: () => import('@/views/permission/index'), name: 'PagePermission', meta: { title: 'Page Permission', roles: ['admin'] // or you can only set roles in sub nav } }, { path: 'directive', component: () => import('@/views/permission/directive'), name: 'DirectivePermission', meta: { title: 'Directive Permission' // if do not set roles, means: this page does not require permission } } ] } ] ``` 3. 在用户登录成功后,根据用户的权限从后台接口获取符合权限的路由,并将其添加到 routes 数组中。 ```javascript import { constantRoutes, asyncRoutes } from '@/router' /** * Use meta.role to determine if the current user has permission * @param roles * @param route */ function hasPermission(roles, route) { if (route.meta && route.meta.roles) { return roles.some(role => route.meta.roles.includes(role)) } else { return true } } /** * Filter asynchronous routing tables by recursion * @param routes asyncRoutes * @param roles */ export function filterAsyncRoutes(routes, roles) { const res = [] routes.forEach(route => { const tmp = { ...route } if (hasPermission(roles, tmp)) { if (tmp.children) { tmp.children = filterAsyncRoutes(tmp.children, roles) } res.push(tmp) } }) return res } const state = { routes: [], addRoutes: [] } const mutations = { SET_ROUTES: (state, routes) => { state.addRoutes = routes state.routes = constantRoutes.concat(routes) } } const actions = { generateRoutes({ commit }, roles) { return new Promise(resolve => { let accessedRoutes if (roles.includes('admin')) { accessedRoutes = asyncRoutes || [] } else { accessedRoutes = filterAsyncRoutes(asyncRoutes, roles) } commit('SET_ROUTES', accessedRoutes) resolve(accessedRoutes) }) } } export default { namespaced: true, state, mutations, actions } ``` 4. 在路由导航守卫中判断用户访问的页面是否在路由中存在,如果不存在则跳转到 404 页面。 ```javascript import router from './router' import store from './store' import { Message } from 'element-ui' import NProgress from 'nprogress' // progress bar import 'nprogress/nprogress.css' // progress bar style import { getToken } from '@/utils/auth' // get token from cookie import getPageTitle from '@/utils/get-page-title' NProgress.configure({ showSpinner: false }) // NProgress Configuration const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist router.beforeEach(async(to, from, next) => { // start progress bar NProgress.start() // set page title document.title = getPageTitle(to.meta.title) // determine whether the user has logged in const hasToken = getToken() if (hasToken) { if (to.path === '/login') { // if is logged in, redirect to the home page next({ path: '/' }) NProgress.done() } else { // determine whether the user has obtained his permission roles through getInfo const hasRoles = store.getters.roles && store.getters.roles.length > 0 if (hasRoles) { next() } else { try { // get user info // note: roles must be a object array! such as: ['admin'] or ,['developer','editor'] const { roles } = await store.dispatch('user/getInfo') // generate accessible routes map based on roles const accessRoutes = await store.dispatch('permission/generateRoutes', roles) // dynamically add accessible routes router.addRoutes(accessRoutes) // hack method to ensure that addRoutes is complete // set the replace: true, so the navigation will not leave a history record next({ ...to, replace: true }) } catch (error) { // remove token and go to login page to re-login await store.dispatch('user/resetToken') Message.error(error || 'Has Error') next(`/login?redirect=${to.path}`) NProgress.done() } } } } else { /* has no token*/ if (whiteList.indexOf(to.path) !== -1) { // in the free login whitelist, go directly next() } else { // other pages that do not have permission to access are redirected to the login page. next(`/login?redirect=${to.path}`) NProgress.done() } } }) router.afterEach(() => { // finish progress bar NProgress.done() }) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值