问题
Could you please tell me what is difference between a component and a View in Aurelia? What are their architectures and What is the difference between their lifecycles?
回答1:
As a rule of thumb, the difference between a view and a component in Aurelia can be summarised as:
- A view in Aurelia is simply put the .html and the styling that comes with it (.scss/.less/.css)
- A view-model in Aurelia is the code behind it (.js/.ts class)
- A component is the combination between a view and view-model, and is glued together automagically by Aurelia
In essence you can say that, with Aurelia, pretty much everything you develop that is either a 'page' or a 'reusable element' can be considered a component. That is what the Aurelia docs on components means with:
Components are the basic building blocks of all Aurelia applications.
But what is currently not described clearly in the docs, at least in my opinion, is that not all components are the same. At least, in terms of their lifecycle in Aurelia. For example, the Component Lifecycle has the following default hooks:
- constructor() - The view-model's constructor is called first.
- created(owningView: View, myView: View)
- bind(bindingContext: Object, overrideContext: Object)
- attached()
- detached()
- unbind()
This lifecycle is the case for all components. But there is a subtle difference that when a component is ran (initialized) through the Router, an additional set of hooks become available:
- canActivate(params, routeConfig, navigationInstruction)
- activate(params, routeConfig, navigationInstruction)
- canDeactivate()
- deactivate()
So a component that goes through the plumbing of the router, e.g. a component where you explicitly navigate to through code, or through a user action like a click, will have additional activation steps in its lifecycle.
As already mentioned earlier, I personally like to refer to these components as "pages", just to give it a clear label and distinct them from for example reusable controls and other components.
回答2:
A component is simply a name often used to describe the pairing of a view and a view-model. A view is the HTML file / template and the view-model is the backing JavaScript file, although it is definitely possible to have a view-only component.
A component can be thought of as a web component although in Aurelia there are a few differences that the docs describe. MDN describes Web Components well
来源:https://stackoverflow.com/questions/45079767/difference-between-a-component-and-a-view-in-aurelia-and-their-lifecycles