返回

剖析 Vue.js 动态路由实现方法(二)

前端

继续上一章的动态路由,下面展示核心部分的js内容:

一、过滤用户只能展示的路由部分:

//假设用户只有一个权限
const permission = {
  show: ['home', 'about', 'contact'],
}

//定义一个方法来判断用户是否有权限查看该路由
const hasPermission = (route) => {
  return permission.show.includes(route.name)
}

//在路由守卫中,判断用户是否有权限查看该路由,如果没有,则重定向到首页
router.beforeEach((to, from, next) => {
  if (!hasPermission(to)) {
    next('/')
  } else {
    next()
  }
})

二、store部分实现持久化数据并生成新的路由:

//在 Vuex store 中定义一个名为 routes 的模块
const store = new Vuex.Store({
  modules: {
    routes: {
      state: {
        routes: []
      },
      mutations: {
        setRoutes(state, routes) {
          state.routes = routes
        }
      },
      getters: {
        getRoutes(state) {
          return state.routes
        }
      }
    }
  }
})

//在组件中,使用 Vuex 的 mapState 和 mapMutations 来获取和修改路由数据
export default {
  computed: {
    ...mapState('routes', ['routes']),
  },
  methods: {
    ...mapMutations('routes', ['setRoutes']),
  },
  created() {
    //从服务器获取路由数据
    axios.get('/api/routes').then((res) => {
      this.setRoutes(res.data)
    })
  },
  render() {
    //使用动态生成的路由
    return (
      <RouterView routes={this.routes} />
    )
  }
}

通过上述代码,我们完成了 Vue.js 动态路由的实现,可以根据用户的权限和服务器返回的数据动态地生成路由,并使用 Vuex 来管理路由数据,实现路由的持久化。