antd组件menu根据url自动高亮和展开
步骤一:封装构造函数
const MenuItem = Menu.Item;
const SubMenu = Menu.SubMenu;
//封装一个构造函数
class MenuNode {
constructor(menuItem, parent=null) {
this.key = menuItem.url || menuItem.auth_name;
this.parent = parent;
}
}
步骤二:定义组件
constructor(props) {
super(props)
this.state = {
//判断是否路由跳转
hash:false,
//判断是否一已经获取数据
finish:false,
collapsed: 0,
defaultOpenKeys: [],
defaultSelectedKeys: []
};
//用来存放遍历完得到的权限数组
this.menuTree = [];
}
// 跳转页面
jumpFn = url => {
this.props.history.push(url)
}
步骤三:挂载完成触发函数遍历权限,生成一个新的数组
//
componentDidMount() {
// 发送异步请求会会获取menu数据,这个时候再序列化menu,通过回调函数监控路由
this.props.getMenu('', () => {
this.initMenu(this.props.menuList);
this.setState({ finish: true })
this.setActiveMenu(this.props.history.location)
})
//监控路由变化
window.addEventListener('hashchange', () => {
this.setState({ hash: true })
})
}
//,通过v-for循环遍历对象this.props.menu,生成一个指定格式的新的数组
initMenu = (config, parent = null) => {
for (let menuItem of config) {
if (menuItem.children) {
//如果menuItem有children则对其children递归执行此方法,并且将当前menuItem作为父级