1. The components

Components: component

For example: we log management system background, found that the left side of the menu bar, the head, in the middle of the data information, administrator information link at the bottom of the and so on, we can think of these different page layout is regarded as a component of one by one, and then put them together like a spell blocks, these components constitute a complete page, as shown in the figure below:

What components do:

  • Reduce the amount of code in the VUE instance
  • Components can be reused:"Code Sharing"
  • Easy for developers to maintain

2. Register globally

After global registration, any VUE instance can use this component.

2.1 Global Registration Syntax:

Vue.component('login',{
  template:'
      
This is the login component
'
}); Copy the code
  • Parameter 1: Name of the component
  • Parameter 2: Component configuration, used in template to write HTML code

2.2 Using Components:

<login></login>  
Copy the code
  • If the component name is humped, the component name must be lowercase word-lowercase when used, for example:
<divid="app"> <! --2. Components use --> <new-component></new-component> </div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.jsVue.component('newComponent', {template: '
      
') Vue.component('newComponent', {template: '
')
' }) const app = new Vue({ el: '#app' })
Copy the code

Running results:

3. Partial registration

Registered components can only be used in the current VUE instance.

    1. Define components first
    1. Components must be registered in the VUE instance
    1. Using the component

3.1 The first registration method

<divid="app"> <! --3Use components. Note: Components can be reused --> <new-component></new-component> <new-component></new-component> </new-component> </new-component> </div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.jsVar newComponent = {template: '
      
I am a local component and can only be used in the current vue instance!
' } const app = new Vue({ el: "
#app", // 2. Register components in vue instance, remember to use components only after registering here: {'newComponent': newComponent}}) Copy the code

Running results:

3.2 Second registration method

Separate the HTML code from template and put it inside the template tag.

<divid="app"> <! --4Use components. Note: Components can be reused --> <new-component></new-component> <new-component></new-component> </new-component> </new-component> </div>

 // 1Declare local component template <template id="newTemplate"> <div> I am a local component that can only be used in the current VUE instance! </div>
</template>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.jsVar newComponent = {template: '#newTemplate'} // 3. Const app = new Vue({el: ")#app", components: { 'newComponent': newComponent } }) Copy the code

Note: Both global and local components can be reused. There must be only one root element in the template, which is typically the div tag.

4. Data in internal data of the component

We know that data from Data can be used in vUE instances, and data from Data can also be used inside components.

  • The data value in the component must be a function that returns an object
  • Use data in data as {{}}
<divid="app"> <! --2. Components use --> <new-component></new-component> </div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.jsVue.component('newComponent', {// The value of data in the component must be a function data: Function (){return {price: 15, MSG:"Keep cooked}}, // {{}} template: '
      

Liu Huaqiang: My God, is this melon ripe? < / p > < p > sell melon: {{MSG}} < / p > < / div > '}) const app = new Vue ({el: '# app'}) < / script >

Copy the code

Running results:

5. Component value transfer

5.1 Parent Components transmit values to child components

  • The property value sent by the parent component must be bound to the property of the child component. In the following example :name indicates that the property of the child component is bound to name, and :name=”childName” indicates that the value of the parent component childName is assigned to the name property of the child component.
  • The child component uses the props attribute. In this example, props:[“name”] means that the child component uses name to receive a value from the parent component.
  • If the properties in props are humped, the properties of the bound child components need to be in the form of a dash. For example, props:[“childAge”] =”age”
<! --4. Parent component binds child component properties to pass values --> <div id="app">
   <p> Parent: {{username}}</p> 
   <child :name="childName" :child-age="age"></child> </div> <! --1Define the component template --> <template id="child"> <div> <p> Son name: {{name}}</p>
        <p> childAge: {{childAge}}</p>
    </div>
</template>

<script>
    // 2Const child = {template: const child = {template:"#child"// The inside property is used to prop :["name"."childAge"]
    }
    const app = new Vue({
        el: "#app",
        data: {
            username: "Zhang Cuishan",
            childName:"Zhang Wuji",
            age:23
        },
        // 3{child}, methods: {},}) </script>Copy the code

5.2 Child Components Transmit values to parent Components

  • Child components with$emit()Triggering event
  • $emit()The first parameter is the event name, and the second parameter is the data to be passed
  • The parent component uses V-ON to listen for events of the child component
<divid="app"> <! --5. Method of passing parameters to the parent component via event binding --> <child@tell="fromChild"> </child> </div> <! --1. Define the child component template --> <template id="child"> <div> <h2> I am the son component, click on me to pass value to the father </h2> < button@click ="change"</button> </div> </template> <script SRC ="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    // 2Const child = {template: Const child = {template:"#child".data() {
            return {
                name: "Zhang Wuji"
            }
        },
        methods: {
            change() {
                // 4.triggers the event this.$emit('tell', this.name);
            }
        },
    }
    const app = new Vue({
        el: "#app",
        data: {
            username: "Zhang Cuishan"
        },
        // 3.register components: {child}, methods: {fromChild(name) {
                console.log("Son:"+name);
            }
        },
    })
</script>
Copy the code

Running results:The above example explains:

    1. When you use a child component, you bind the parent component’s fromChild method with @tell
    1. Click the button of the child component to pass$emit()When a tell event is triggered, the parent listens for the child’s tell event via V-ON, where @tell is short for V-ON: Tell. The parent passes the listening data to its fromChild method.
    1. The parent component’s fromChild method prints out the data

6. Component access

6.1 Parent Component accessing child component data

  • Used when working with child components$refsDefine an alias for the child component
  • useThis.$refs. Child component aliasYou can get child component information
<divid="app"> <! --4Use component, alias child component by ref --> <new-component ref="firstChild"></new-component> <hr> <button @click</button> </div> <! --1Declare a local component template --> <template id="newTemplate"> <div> I am a local component that can only be used in the current Vue instance! </div> </template> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    // 2Var newComponent = {template:'#newTemplate', data: function () {// This function must return an object {film:"Sweep the storm"}}} / /3.register component const app = new Vue({el:"#app",
        data: {
            msg: ""
        },
        components: {
            'newComponent': newComponent
        },
        methods: {
            getFilmName() {/ /5.this.$refs.firstChild.film gets the property console of the child component.log("Recent Hits:"+this.$refs.firstChild.film);
            }
        },
    })
</script>
Copy the code

Running results:

6.2 Child Component Accessing Parent Component Data

  • usethis.$parentAccessing the parent component
<divid="app"> <! --4. Use components --> <new-component></new-component> </div> <! --1--> <template id="newTemplate"> <div>
        <h2> This is a child component! </h2>
        <hr>
        <button @click</button> </div> </template> <script SRC ="getFilmName""https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    // 2Var newComponent = {template:'#newTemplate',
        methods: {
            getFilmName(){
                console.log("Recent Hits:"+this.$parent.film); }}} / /3.register component const app = new Vue({el:"#app",
        data: {
            film: "Sweep the storm"
        },
        components: {
            'newComponent': newComponent
        },
        methods: {

        },
    })
</script>
Copy the code

Running results:

7. Component slot

    1. Create a component and use<slot> Default contents </slot>Show the default content
    1. When using components, the content in the middle of the component tag overwrites the content in the slot tag
    1. Using component slots can increase code reuse

7.1 Anonymous Slot

Set default values. Component labels overwrite default values if they have values, and display default values if they do not.

<divid="app"> <! --2. The nested content in all component tags replaces the slot, and if no value is passed, the default value in the slot is used --> <final></final> <final> /final> <final> Gao Mingyuan is the big boss! </final> <final> Wang Zheng is the big boss! </final> </div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascriptVue.component('final', {template: vue.component ('final', {template: vue.component ('final', {template: vue.component)); ` < div > < span > anti-triad storm finale: < / span > < slot > who is the big boss? < / slot > < / div > `}); const app = new Vue({ el: '#app', data: { } }); Copy the code

Running results:

7.2 Named Slot

You can set a value for a slot with a specific name when using a component.

<divid="app"> <! --2. The nested content in all component tags replaces the slot, and if no value is passed, the default value in the slot is used --> <final></final> <final> </final> <final> Gao Mingyuan is the big boss! </final> <final><span slot="boss" style="color:red"> < p style = "max-width: 100%; clear: both; min-height: 1em; !    https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascriptVue.component('final', {template: '
      
boss"> < p style = "max-width: 100%; ` }); const app = new Vue({ el: '#app', data: { } }); Copy the code

Running results: