concept
Component systems are another important concept for Vue because it is an abstraction that allows us to build large applications from small, independent, and often reusable components. If you think about it, almost any type of application interface can be abstracted as a component tree:
!!!!!!!!! Remember: the reusable structure, style, and functionality of the page, separated into a single file;
Features: Easy to organize and manage code, easy to maintain and extend maintenance
The difference between componentization and modularization:
Modularity: Partitioning from the point of view of code logic; It is convenient for hierarchical code development to ensure the single componentization of each function module: componentization of the front end is divided from the perspective of UI interface to facilitate the reuse of components;
Global components
These components are registered globally. That is, they can be used in the template of any newly created Vue root instance (New Vue) after registration.
1. Register
Vue.component('MyDemo'{template: '<div> global component registration for this </div>'})Copy the code
2. Instantiate Vue
var vm = new Vue({
el:'#app',})Copy the code
3. Use components
<div id="app">
<my-demo></my-demo>
</div>
Copy the code
!!!!!!!!! Matters needing attention:
*** must be registered *** to use. And the registration is written before the instance. Otherwise, it won’t work. Component names cannot use browser-supported labels. Such as: div, the article…
Local components
Components are registered via Vue.component(), called global registration, which means they can be used anywhere in the instance.
The global component can also cause problems if we register the global component in a project in the future, but we no longer use it. This will result in the useless global component being packaged into the project as well. We can solve this problem by using a local registry, which registers components as needed.
How local components are registered
1. Define components via plain JavaScript objects:
var ComponentA = { /* ... */ }
var ComponentB = { /* ... */ }
var ComponentC = { /* ... */ }
Copy the code
2. Register the components you want to use in the Components option:
new Vue({
el: '#app',
components: {
ComponentA,
ComponentB
}
})
Copy the code
3. Use note where is the registration, so this component can only be used here
<component-a></component-a>
<component-b></component-b>
Copy the code
Pay attention to
Here we have not registered ComponentC, so it can not be used. Local components must be registered before they can be used. Otherwise, an error will be reported