How Vue creates components

The concept of components

The component system is Vue.jsone of the important concepts. It provides an abstraction that allows us to build large applications using independently reusable small components. Any type of application interface can be abstracted into a component tree:
Insert picture description here
each component Independent of each other, components need to be created and registered before they can be used. Registration is divided into global registration and local registration.

Global registration

grammar

Vue.component('component-name', { 
	/* ... */ 
})

Using the Vue.component()方method, two parameters can be passed, the first parameter is the component name is recommended (kebab-case) are named.

Examples

<div id="app">
    <component-name></component-name> <!-- 以标签形式使用组件 -->
</div>

<script>
    // 定义一个名为 component-name 的新组件
    Vue.component('component-name', {
        //组件内容写这里
        template: "<div>这是一个全局组件</div>",
    })
    
    //声明一个vue实例
    var vueApp = new Vue({
        el: '#app',
    })
</script>

Precautions

  • The global component must be written before the Vue instance is created before it takes effect under the root element
  • The first level in the template can only have one label, not parallel
  • Components datamust be functions
  • Tags will be nested HTMLrestrictive rules, such as: <ul>, <ol>, <table>, <select>limiting the elements can be wrapped in it, and some like <option>elements so would only appear in some other internal elements

Partial registration

grammar

var child={
  template:"<h1>我是局部组件</h1>"
};

new Vue({
  el: "#app1",
  components:{
    "child-component": child
  }
});

Use Vueexample there is an option componentsregister local assembly, after the registration is valid only at the instance scope

Examples

<div id="app">
  <child-component></child-component>
</div>

var child = {
   template:"<button @click='add'>我是局部组件:{{m}}</button>",
   data:function(){
     return {m:1}
   },
   methods:{
     add:function(){
       this.m++
     }
   }
 };
 
 new Vue({
   el: "#app",
   components:{
     "child-component": child
   }
 })

Precautions

  • Local components are registered in the calling parent component and can only be used in this scope
  • Global components and local components, data must also be a function
  • Tags will be nested HTMLrestrictive rules, such as: <ul>, <ol>, <table>, <select>limiting the elements can be wrapped in it, and some like <option>elements so would only appear in some other internal elements

Want to know how the parent-child component communicates, please read: " How the parent-child component communicates "

Reference materials:
https://cn.vuejs.org/v2/guide/components-registration.html

Published 147 original articles · praised 49 · 160,000 views +

Guess you like

Origin blog.csdn.net/bigbear00007/article/details/104886972