Ember.js动态组件

5

我有两个模型AdminUser。 我的应用程序模板如下:

//application.hbs
{{outlet}}
{{header-nav}}

如果可能的话,我想让{{header-nav}}可定制化,我解释一下: 如果管理员已经认证,我想呈现组件{{admin-header}}, 如果用户已经认证,它应该呈现{{user-header}}。 如何在application.hbs中动态构建要呈现的内容?

2个回答

3
您可以在应用控制器中定义isAdmin计算属性,代码如下:
// application controller 
isAdmin: Ember.computed(function() {
  // your logic here
})

// application template
{{#if isAdmin}}
  {{admin-header}}
{{else}}
  {{user-admin}}
{{/if}}

或者您可以将其作为具有 isAdmin 属性的 header-nav 组件进行包装,如下所示:

// application template
{{header-nav isAdmin=isAdmin}}

更新 (使用 ember-simple-auth 为 @Grimmy 提供详细信息)

1) 将 currentUser 注入到 session 中(例如,https://dev59.com/-Izda4cB1Zd3GeqPhAjE#30894082)。

2) 在 beforeModel 钩子中解析 currentUser 并设置 currentUser 控制器属性:

//route
beforeModel: function() {
  var self = this;
  this.session.get('currentUser').then(function(user) {
    self.controllerFor( self.routeName ).set('currentUser', user);
  },function() {
    self.controllerFor( self.routeName ).set('currentUser', null);
  });
}

//controller
isAdmin: Ember.computed('currentUser.role', function() {
  return (this.get('currentUser.role') === 'admin');
}),

//template
{{#if isAdmin}}
  {{admin-header}}
{{else}}
  {{user-admin}}
{{/if}}

或者如上所述。
//controller
roleBasedComponentName: Ember.computed('currentUser.role', function() {
  return ((this.get('currentUser.role') === 'admin') ? 'admin-header' : 'user-header');
})

//template
{{component roleBasedComponentName user=currentUser}}

请给我一个完整的控制器示例,可以吗? - Grimmy
1
你想看点特别的东西吗? - artych
在路由中,“nil”是什么意思? - Grimmy
我正在使用ember-simple-auth 0.7.3,我尝试了你的解决方案,但出现了以下错误:“处理路由时出错:index”“this.session.get(...)未定义”“beforeModel @ http://localhost:4200/,有什么想法吗?(不好意思再次打扰你)” - Grimmy
看起来 this.session 是空的。你可能没有正确地包含 ApplicationRouteMixinAuthenticatedRouteMixin,或者其他什么问题。请参考 https://github.com/simplabs/ember-simple-auth#the-session 了解如何在路由中使用 session。还有为什么不使用 '0.8.0' 版本呢? - artych
显示剩余3条评论

3

你可以使用{{component}}助手,但首先需要确定组件名称,在你的控制器中:

nameForComponent: Ember.computed('user.isAdmin', function()  {
// if admin return admin-header else user-header
})

那么,在您的模板中:

然后,在您的模板中:

{{component nameForComponent}} 

它是为这些使用情况而设计和引入的,不久前推出。

您还可以更花哨一些:

{{component (if user.isAdmin 'admin-header' 'user-header') }} 

非常抱歉回复晚了,感谢您的答案。请问在哪个控制器中定义nameForComponent(我是Ember的新手)? - Grimmy
1
在应用控制器或headernav组件中,取决于您使用组件助手的模板。 - Daniel Kmak
好的,你能给我一个例子来展示应该返回nameForComponent吗?请注意,我正在使用Ember-simple-auth进行身份验证,并且在我的用户中有一个角色属性,它可以是“admin”或“user”。 好的,你能给我一个例子来展示应该返回nameForComponent吗?请注意,我正在使用Ember-simple-auth进行身份验证,并且在我的用户中有一个角色属性,它可以是“admin”或“user”。 - Grimmy
1
nameForComponent 应该返回组件名称 - 字符串 admin-headeruser-header - Daniel Kmak
最后一个问题,使用ember-simple-auth获取当前用户(角色)的最佳方法是什么? - Grimmy
我没有使用过这个插件。 - Daniel Kmak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接