1. vuex
- 数据管理
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
state: {}, // 存储数据的状态
getters: {}, // 获取vuex数据(state)的统一接口
mutations: {}, // 存vuex数据(state)的统一接口
actions: {}, // vuex内的异步操作接口
modules: {}, // 子模块
简单应用:
import Vue from 'vue'
import Vuex from 'vuex'
import fetch from './util/fetch.js'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
is_auth: null,// 0: 未认证 1: 认证成功
},
getters: {
is_auth: function (state) {
return state.is_auth;
}
},
mutations: {
setAuth: function (state, is_auth) {
state.is_auth = is_auth;
}
},
actions: {
GetInfo({commit, state}) {
//获取用户基本信息
return new Promise(function (resolve, reject) {
fetch({
url: "user/auto_login",
method: "post",
data: {}
}).then(function (res) {
commit('setAuth', res.data.is_auth);
resolve(res);
}).catch(function (err) {
reject(err);
});
})
}
}
})
2. vue-router
- 路由跳转
router.push(location, onComplete?, onAbort?)
// 字符串
router.push('home')
// 对象
router.push({ path: 'home' })
// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
router.replace(location, onComplete?, onAbort?)
跟 router.push
很像,但不会向 history 添加新记录,而是替换掉当前的 history 记录。
router.go(n)
这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)
。
// 在浏览器记录中前进一步,等同于 history.forward()
router.go(1)
// 后退一步记录,等同于 history.back()
router.go(-1)
// 前进 3 步记录
router.go(3)
// 如果 history 记录不够用,那就默默地失败呗
router.go(-100)
router.go(100)
- 路由守卫
全局前置守卫
router.beforeEach((to, from, next) => {
// ...
})
to: Route
: 即将要进入的目标路由from: Route
: 当前导航正要离开的路由next: Function
: 一定要调用该方法来 resolve 这个钩子。执行效果依赖next
方法的调用参数。next()
: 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。next(false)
: 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到from
路由对应的地址。next('/')
或者next({ path: '/' })
: 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向next
传递任意位置对象,且允许设置诸如replace: true
、name: 'home'
之类的选项以及任何用在router-link
的to
prop 或router.push
中的选项。next(error)
: (2.4.0+) 如果传入next
的参数是一个Error
实例,则导航会被终止且该错误会被传递给router.onError()
注册过的回调。
全局后置钩子
全局后置钩子,然而和守卫不同的是,这些钩子不会接受 next
函数也不会改变导航本身
router.afterEach((to, from) => {
// ...
})
组件内的守卫
beforeRouteEnter (to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
},
beforeRouteUpdate (to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
},
beforeRouteLeave (to, from, next) {
// 导航离开该组件的对应路由时调用
// 可以访问组件实例 `this`
}
beforeRouteEnter
守卫 不能 访问 this
,因为守卫在导航确认前被调用,因此即将登场的新组件还没被创建。可以通过传一个回调给 next
来访问组件实例。在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。
beforeRouteEnter (to, from, next) {
next(vm => {
// 通过 `vm` 访问组件实例
})
}
beforeRouteUpdate
和 beforeRouteLeave
来说,this
已经可用了,所以不支持传递回调,因为没有必要了。
beforeRouteUpdate (to, from, next) {
// just use `this`
this.name = to.params.name
next()
}
离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false)
来取消。
beforeRouteLeave (to, from , next) {
const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
if (answer) {
next()
} else {
next(false)
}
}
- 路由鉴权
给路由添加鉴权
这里我们使用全局的守卫,来进行整体的路由鉴权。
main.js中全局前置守卫beforeEach方法中:
router.beforeEach(function (to, from, next) { if (getToken()) { store.commit('setToken', getToken()); //获取用户信息 store.dispatch('autolog').then(res => { if (store.state.client.routers.length <= 2) { // 初始化路由 store.dispatch("getRoleList").then(re => { let arr = []; re.data.forEach(function (ite) { recurRouter(ite, arr); }); setC("jgList", arr.join(",")); store.dispatch('GenerateRoutes', arr).then(function (r) { router.addRoutes(store.getters.addRoutes); next() }).catch(function (e) {}) }).catch(er => {}); } }).catch(err => {}); if (to.name == 'login') { next('/') } else { next() } } else { if (white.indexOf(to.name) > -1) { next() } else { next({name: 'login'}) } } }) function recurRouter(routerItem, arr){ if (!routerItem) return; arr.push(routerItem.fcode); if (routerItem._child && routerItem._child.length > 0){ routerItem._child.forEach(function (item) { recurRouter(item, arr); }) } }
store中处理权限路由的方法:
actions: { GenerateRoutes({commit}, data) { return new Promise(function (resolve, reject) { const roles = data; let accessedRouters; accessedRouters = filterAsyncRouter(rolesRouter, roles); commit('setrouters', accessedRouters); resolve(); }) } }
filterAsyncRouter与hasPermission方法:
//验证权限的函数
function filterAsyncRouter(asyncRouterMap, roles) {
const accessedRouters = asyncRouterMap.filter(route => {
if (hasPermission(roles, route)) {
if (route.children && route.children.length) {
route.children = filterAsyncRouter(route.children, roles)
}
return true
}
return false
});
return accessedRouters;
}
function hasPermission(roles, route) {
if (route.meta && route.meta.fcode) {
return roles.some(role => route.meta.fcode == role)
} else {
return true
}
}
router路由表中配置权限fcode
const qyList = [101, 102, 103, 104]; const gsList = [201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 999]; const jgList = ["0201", "0202", "0203", "0204", "0205"]; const qyHeadList = ["01", "03", "04", "05"]; export const rolesRouter = [ { path: "/", name: "index", component: _imp('404/parent'), redirect: function (to) { let type = parseInt(getC("type")); if (getC("type")) { return {name: "gs"}; } else { removeToken(); removeC("type"); removeC("jgList"); return {name: "login"} } }, children: [ { path: '/gs', name: 'gs', component: _imp('gs/gs'), redirect: function (to) { if (getC("type") == 207) { return {name: 'bankOverview'}; } else { return {name: 'gsoverview'}; } }, children: [ { path: 'overview', name: 'gsoverview', component: _imp('gs/overview/overview'), meta: {title: '首页', topShow: 2, fcode: "01"} }, { path: 'bankOverview', name: 'bankOverview', component: _imp('gs/bankOverview/bankOverview'), meta: {title: '首页', topShow: 3, fcode: "01"} }, { path: 'supervise', name: 'supervise', component: _imp('gs/supervise/supervise'), redirect: {name: 'work_clip'}, meta: { title: '抽查', case: '广告抽查', icon: 'static/icon/icon1.png', topShow: true, fcode: "02", }, children: [ { path: 'work_clip', name: 'work_clip', redirect: function () { let aliveArray = []; if (getC("jgList")){ let arr = getC("jgList").split(","); jgList.forEach(item => { if (arr.indexOf(item) >= 0) { aliveArray.push(item); } }); } if (aliveArray.length > 0) { switch (aliveArray[0]) { case "0201": return {name: "my_evidence_main"}; case "0202": return {name: "double_random_main"}; case "0203": return {name: "detected_ad_main"}; case "0204": return {name: "clue_store_main"}; case "0205": return {name: "certificated_clue_main"}; default: return {name: "my_evidence_main"}; } }else { return {name: "my_evidence_main"}; } }, meta: {title: '我的监管', icon: 'static/icon/warning_center.png'}, component: _imp('gs/supervise/work_clip/work_clip'), children: [ { path: 'my_evidence', name: 'my_evidence_main', meta: {title: '我的出证夹', fcode: "0201"}, component: _imp('gs/supervise/work_clip/my_evidence/index'), redirect: {name: "my_evidence"}, children: [ { path: 'my_evidence', name: 'my_evidence', meta: {title: '我的出证夹'}, component: _imp('gs/supervise/work_clip/my_evidence/my_evidence') }, { path: 'apply_success', name: 'apply_success', meta: {title: '出证成功', leftHidden: true}, component: _imp('gs/supervise/work_clip/my_evidence/apply_success/apply_success') }, { path: 'apply_evidence', name: 'apply_evidence', meta: {title: '申请出证', leftHidden: true}, component: _imp('gs/supervise/work_clip/my_evidence/apply_evidence/apply_evidence') }, { path: 'manage_agent', name: 'manage_agent', meta: {title: '管理', leftHidden: true}, component: _imp('gs/supervise/work_clip/my_evidence/manage_agent/manage_agent') }, { path: 'evidence_detail', name: 'evidence_detail', meta: {title: '线索详情', leftHidden: true,}, component: _imp('gs/supervise/work_clip/my_evidence/evidence_detail/evidence_detail') }, ] }, { path: 'double_random', name: 'double_random_main', meta: {title: '双随机', fcode: "0202"}, component: _imp('gs/supervise/work_clip/double_random/index'), redirect: {name: "double_random"}, children: [ { path: 'double_random', name: 'double_random', meta: {title: '双随机'}, component: _imp('gs/supervise/work_clip/double_random/double_random') }, { path: 'create_double_random', name: 'create_double_random', meta: {title: '新建双随机任务', leftHidden: true}, component: _imp('gs/supervise/work_clip/double_random/create_double_random/create_double_random') }, { path: 'double_random_detail', name: 'double_random_detail', meta: {title: '计划信息', hidden: true}, component: _imp('gs/supervise/work_clip/double_random/double_random_detail/double_random_detail') }, ] }, { path: "detected_ad", name: "detected_ad_main", meta: {title: "复核", fcode: "0203"}, component: _imp("gs/supervise/work_clip/detected_ad/index"), redirect: {name: "detected_ad"}, children: [ { path: "detected_ad", name: "detected_ad", meta: {title: "广告复核"}, component: _imp("gs/supervise/work_clip/detected_ad/detected_ad") }, { path: 'detected_ad_detail', name: 'detected_ad_detail', meta: {title: '广告详情', hidden: true}, component: _imp('gs/supervise/work_clip/detected_ad/detected_ad_detail/detected_ad_detail') }, { path: 'detected_ad_judge', name: 'detected_ad_judge', meta: {title: '批量违规判定', hidden: true}, component: _imp('gs/supervise/work_clip/detected_ad/detected_ad_judge/detected_ad_judge') }, ] }, { path: 'clue_store', name: 'clue_store_main', meta: {title: '线索库', fcode: "0204"}, component: _imp('gs/supervise/work_clip/clue_store/index'), redirect: {name: "clue_store"}, children: [ { path: 'clue_store', name: 'clue_store', meta: {title: '线索库'}, component: _imp('gs/supervise/work_clip/clue_store/clue_store') }, { path: 'clue_detail', name: 'clue_detail', meta: {title: '线索详情', hidden: true,}, component: _imp('gs/supervise/work_clip/clue_store/clue_detail/clue_detail') }, { path: 'clue_change_judge', name: 'clue_change_judge', meta: {title: '更改违规判定', leftHidden: true,}, component: _imp('gs/supervise/work_clip/clue_store/change_judge/change_judge') }, ] }, { path: "certificated_clue", name: "certificated_clue_main", meta: {title: "已申请的出证", fcode: "0205"}, component: _imp("gs/supervise/work_clip/certificated_clue/index"), redirect: {name: "certificated_clue"}, children: [ { path: "certificated_clue", name: "certificated_clue", meta: {title: "已申请的出证"}, component: _imp("gs/supervise/work_clip/certificated_clue/certificated_clue") }, { path: 'clue_progress', name: 'clue_progress', meta: {title: '进度详情', leftHidden: true}, component: _imp('gs/supervise/work_clip/certificated_clue/clue_progress/clue_progress') }, ] }, ] } ] }, { path: 'banknoticeDetail', name: 'banknoticeDetail', component: _imp('home/notice/noticeDetail'), meta: {title: '公告详情', topShow: false,hidden:true} }, { path: "analysis", name: "analysis", component: _imp("gs/analysis/analysis"), redirect: {name: "supervision"}, meta: { title: "分析", case: "数据分析", icon: "static/icon/icon1.png", topShow: true, fcode: "06" }, children: [ { path: "supervision", name: "supervision", redirect: {name: "trend_analysis"}, meta: {title: '监管分析', icon: 'static/icon/warning_center.png'}, component: _imp('gs/analysis/supervision/supervision'), children: [ { path: "trend_analysis", name: "trend_analysis", meta: {title: "数据分析", fcode: "0601"}, component: _imp("404/defend") }, ] } ] }, { path: "gs_report", name: "gs_report", component: _imp("gs/report/report"), meta: { title: "报告", case: "报告报表", icon: 'static/icon/report1.png', topShow: true, fcode: "04" }, redirect: {name: "gs_data_report"}, children: [ { path: "gs_data_report", name: "gs_data_report", meta: {title: '数据报告', icon: 'static/icon/report2.png'}, component: _imp('gs/report/data_report/data_report'), redirect: {name: "gs_my_report"}, children: [ { path: "gs_my_report", name: "gs_my_report", meta: {title: "我的报告", fcode: "0401"}, component: _imp("gs/report/data_report/my_report/my_report") } ] } ] }, { path: "setting", name: "setting", component: _imp("gs/setting/setting"), meta: { title: "系统", case: "设置", icon: 'static/icon/report1.png', topShow: true, fcode: "05" }, redirect: {name: "manage"}, children: [ { path: "manage", name: "manage", meta: {title: '系统设置', icon: 'static/icon/report2.png'}, component: _imp('gs/setting/manage/manage'), redirect: {name: "role_manage"}, children: [ { path: "role_manage", name: "role_manage", meta: {title: "账户信息", fcode: "0506"}, component: _imp("gs/setting/manage/role_manage/role_manage") }, { path: "person_manage", name: "person_manage", meta: {title: "用户管理", fcode: "0505"}, component: _imp("gs/setting/manage/person_manage/person_manage"), redirect: {name: "person_list"}, children: [ { path: "person_list", name: "person_list", meta: {title: "用户管理"}, component: _imp("gs/setting/manage/person_manage/person_list/person_list") }, { path: "create_person", name: "create_person", meta: {title: "新增用户"}, component: _imp("gs/setting/manage/person_manage/create_person/create_person") }, { path: "person_detail", name: "person_detail", meta: {title: "管理用户"}, component: _imp("gs/setting/manage/person_manage/person_detail/person_detail") } ] } ] } ] }, ] } ] } ]; export const whiteRoutes = [ {path: '/login', name: 'login', meta: {title: '登陆'}, component: _imp('login/login')}, {path: '/404', name: '404', component: _imp('404/404')}, {path: '*', redirect: '/404', name: '*', meta: {title: '404页面'}} ]; export default new Router({ routes: whiteRoutes });