项目边做边总结
1.定义路由时,分
应用路由,需权限控制
使用前要验证权限 : router.beforeEach
dispatch:含有异步操作,例如向后台提交数据,写法: this.$store.dispatch('mutations方法名',值)
commit:同步操作,写法:this.$store.commit('mutations方法名',值)
vuex store的知识
const mutations = { /** * 更新登录用户信息 * @param state * @param payload */ //state是默认参数吧。。。。。后面action里面调用的时候传的就只有payload setCurrentUser (state, payload) { state.currentUser = Object.assign(state.currentUser, payload) }, setAuthorities (state, payload) { state.authorities = payload }, setRoutes: (state, routes) => { state.addRoutes = routes state.routes = cloneDeep(constantRoutes).concat(routes) } }
this.$store.commit("mutations名字",参数)
this.$store.dispatch("actions名字",参数)
actions里面 contentc.commit参数 = {commit} = 这叫变量解构赋值
commit("mutations名字",参数)
这两种写法的不同在于 action里面可以做异步操作
router.beforeEach(async (to, from, next) => { if (to.path === '/error') { next() //进入下一个钩子函数 } else { if (getToken() && getToken() !== null) { // 已经登录存在有token // 如果已经生成过路由,不需要再次生成动态路由 if (addRouteFlag) { next() //进入下一个钩子函数 } else { // 同步获取用户信息,动态添加权限路由 await store.dispatch('syncCurrentUser') let accessRoutes = await store.dispatch('generateRoutes') let newRouteTmp = [] newRouteTmp.push(accessRoutes) router.addRoutes(newRouteTmp) addRouteFlag = accessRoutes next({ ...to, replace: true }) } } else { // 还没有登录 jquery.getScript('http://172.16.13.64:9995/cloudiip-cas/open-login-api.jsp?_=1556259574232', async () => { let loginCode = auth.code if (loginCode === 1001) { // 其他地方没有登录 let location = window.location.href let locTemp = encodeURIComponent(location) window.location.href = 'http://172.16.13.64:9995/cloudiip-cas/login?service=' + locTemp next() } else if (loginCode === 1) { // 其他地方已经登录 if (auth.message) { setToken(auth.message) if (addRouteFlag) { next() } else { // 同步获取用户信息,动态添加权限路由 let authorities = await store.dispatch('syncCurrentUser') let accessRoutes = await store.dispatch('generateRoutes', authorities, { root: true }) let newRouteTmp = [] newRouteTmp.push(accessRoutes) router.addRoutes(newRouteTmp) addRouteFlag = accessRoutes next({ ...to, replace: true }) } } else { next({ path: '/error' }) } } else { // 其他情况 next({ path: '/error' }) } }) } } })
常用无权限控制路由
常用路由就直接使用
const router = new Router({
scrollBehavior: () => ({ y: 0 }),//跳转到一个新的页面的时候,显示最顶端
routes: constantRoutes
})