Aurelia 在 ViewModel 上设置元素

Aurelia set element on ViewModel

您将如何从 ViewModel 向视图添加组件。例如,我有以下内容:

我将服务注入到组件中。然后从组件中获取数据,当我得到响应时,我将 data 属性 设置为获取的数据。在此之后,我想将组件安装到 View 并将获取的数据作为可绑定的。

this.service.get()
.then(response => response.json())
.then(data =>{ 
    this.data = data.results
    //Mount element to View here: <component data.bind="data"></component>
})

我问这个问题是因为如果我在获取时和视图上将值设置为:

<component data.bind="data"></component>

它传递一个空对象。我已尝试在 canActivateactivate 方法上使用该服务。

组件:

export class Component{
   @bindable data
   bind(){
      console.log(this.data)
   }
}

绑定到的 "data" 字段是使用您的组件的 ViewModel 上的字段,而不是您组件中的字段。

我将您的代码复制到要点中,并 运行 它在 gist.run 此处:https://gist.run/?id=04907ff8d8b6d8b4aee625669d8571a3

它按我的预期运行。我什至更新了它以在承诺中设置数据。

现在,如果您想在 data 属性 更改时收到通知,您需要实现一个名为 ${propertyName}Changed(newValue, oldValue) 的函数,因此在这种情况下,dataChanged(newValue, oldValue).我创建了一个单独的要点来展示您可能希望如何更改代码:https://gist.run/?id=34a01ca3f600470691d5b91c9131f33b

您会注意到在我的代码中我没有使用 newValueoldValue 参数。我这样做是为了让您知道 Aurelia 仍然设置 属性 值。当 属性 值改变时,回调只是让你的代码做一些事情。