1.概述
角色用户的权限是有一定的顺序的,但是,我们刚刚的显示并无顺序,顺序就按照我们数据库所加载的,这样显示很不友好
2.处理思路
首先,我们的问题就出在获取数据时,所以应该定位到创建模型时的get_menu_dict()函数中。此时,我们应该对使用sorted给对象(角色)排序,可是对象是不可以进行排序的。此时,我们就应该使用自定义关键词给对象进行排序即可。
3.主要代码
<!-- components/power/Role.vue -->
# 角色管理
class Role(db.Model):
__tablename__ = 't_role'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(32), unique=True, nullable = True)
desc = db.Column(db.String(32))
# backref反向关联,方便子表查询主表数据
users = db.relationship('User', backref='role')
menus = db.relationship('Menu', secondary = trm)
def to_dict(self):
return {
'id':self.id,
'name': self.name,
'desc':self.desc,
'menu': self.get_menu_dict()
}
def get_menu_dict(self):
menu_list = []
# 自定义排序
menus = sorted(self.menus, key= lambda temp:temp.id)
for m in menus:
# 一共就两级,二级的应该放在一级的当作children输出
if m.level == 1:
first_dict = m.to_dict()
first_dict['children'] = []
for s in menus:
# 只有二级才需要加入到children,并判断是否为关联关系
if s.level == 2 and s.pid == m.id:
first_dict['children'].append(s.to_dict())
menu_list.append(first_dict)
return menu_list