Vue tutorial details V (components)

Posted by Ajdija on Mon, 21 Feb 2022 12:24:01 +0100

Components are reusable Vue instances, so they receive the same options as new Vue, such as data, computed, watch, methods, and lifecycle hooks. The only exceptions are instance specific options like el.

Components are collections of code (html/css/js) and resources (mp3/mp4/ttf/zip) used to achieve local (specific) functional effects

Advantages of components: reusable code, simplifying project coding and improving operation efficiency;

Classification of components: single file components (a file contains only one component, which is often used in large projects), non single file components (a file contains n components); Local components; Global components

Create component:

First, let's talk about local components:

Vue is usually used Extend to create components (note that it is separate from inheritance, and inheritance is extensions), and the configuration items are the same as those of v general ue instances, but el cannot be written (because the components are created to serve many places, all components must be managed by a vm, and the vm determines which container to serve);

If the el configuration item is written in the component, the following error will be reported:

In addition, the data configuration item in the component cannot be written in the form of an object as before. It should be wrapped in the form of a function (see that there are two ways to write data before) and returned with return (if the data configuration item is defined in the form of an object, the data of multiple pages of the referenced component will be modified accordingly if the data of one page is modified), For example:

<script>
        let data = {
            A1: 0,
            A2: 1
        }
        const x1 = data;
        const x2 = data;
</script>

Define data in an object-oriented manner and modify x1, then x2 will be modified accordingly;

However, if it is defined as a functional expression, the instances generated by the called function are independent and do not affect each other;

<script>
function data() {
            return {
                A1: 0,
                A2: 1
            }
        }
        const x1 = data();
        const x2 = data();
</script>

An example of creating a complete component is as follows:

// Local component creation
const students = Vue.extend({
            data() {
                return {
                    studentName: 'Xiao Ming',
                    studentClass: 'Third grade'
                }
            }
        })

In general, Vue Extend is omitted as follows:

const students = {
            data() {
                return {
                    studentName: 'Xiao Ming',
                    studentClass: 'Third grade'
                }
            }
        }

Register local components

As mentioned above, the components are uniformly managed by vue instances created by new Vue (generally set as vm), which components are managed by vm configuration, and the components are registered with the configuration item components;

<script>     
// Create vm
const vm = new Vue({
   el: '#root',
   // Register local components
   components: {
       students: students
   }
})
</script>

The components configuration item still stores the value of key: value, where key refers to the component name used as a label and value refers to the defined component name. If key and value are the same, it can be omitted:

<script>    
   // Create vm
   const vm = new Vue({
      el: '#root',
      // Register local components
      components: {
         students
      }
   })
</script> 

Authoring component labels

Use the key value of the components in the previous step as a tag, such as students,

<body>
    <div id='root'>
    <!-- Authoring component labels -->
        <students></students>
    </div>
    <script>
        // Building local components
        const students = {
                data() {
                    return {
                        studentName: 'Xiao Ming',
                        studentClass: 'Third grade'
                    }
                }
            }
            // Create vm
        const vm = new Vue({
            el: '#root',
            // Register local components
            components: {
                students
            }
        })
    </script>
</body>

At this time, because the template configuration item is not defined in the students component, the following error will be reported:

Amend to read:

<body>
    <div id='root'>
        <!-- Authoring component labels -->
        <students></students>
    </div>
    <script>
        // Building local components
        const students = {
                data() {
                    return {
                        studentName: 'Xiao Ming',
                        studentClass: 'Third grade'
                    }
                },
                template: `
                        <span>{{studentName}}</span>
                        <span>{{studentClass}}</span>`
            }
            // Create vm
        const vm = new Vue({
            el: '#root',
            // Register local components
            components: {
                students
            }
        })
    </script>
</body>

Still report an error,

The prompt obviously means that the component can only contain one root element, so you can wrap the contents of the template in a parent element to fix this problem,

<body>
    <div id='root'>
        <!-- Authoring component labels -->
        <students></students>
    </div>
    <script>
        // Building local components
        const students = {
                data() {
                    return {
                        studentName: 'Xiao Ming',
                        studentClass: 'Third grade'
                    }
                },
                template: `
                    <div>
                        <span>{{studentName}}</span>
                        <span>{{studentClass}}</span>
                    </div>`
            }
            // Create vm
        const vm = new Vue({
            el: '#root',
            // Register local components
            components: {
                students
            }
        })
    </script>
</body>

A simple partial component has been completed, and the page is shown as follows:

 

Component labels can also be written as self closing labels. For example, the above components can be written as < students / >

However, this label writing method is generally used in conjunction with the scaffold, otherwise the label will only be rendered once, and the subsequent component labels will not be parsed;

<body>
    <div id='root'>
        <!-- Authoring component labels -->
        <students/>
        <students/>
        <students/>
    </div>
    <script>
        // Building local components
        const students = {
                data() {
                    return {
                        studentName: 'Xiao Ming',
                        studentClass: 'Third grade'
                    }
                },
                template: `
                    <div>
                        <span>{{studentName}}</span>
                        <span>{{studentClass}}</span>
                    </div>`
            }
            // Create vm
        const vm = new Vue({
            el: '#root',
            // Register local components
            components: {
                students
            }
        })
    </script>
</body>

As above, three < students / > components are written, but only one will be parsed on the page, as shown below:

In addition, there are many ways to define component tag names:

If the label is composed of one word, it can be written as a name composed of all lowercase letters or an English name with uppercase letters, such as students and students

If the label consists of multiple words, it can also be divided into two ways,

Kebab case naming method: that is, the naming method separated by dashes (all lowercase), such as my school;

PascalCase naming method: that is, the hump naming method with capital letters, such as MySchool;

Let's talk about global components:

Global components are defined as components used globally. They are different from local components when they are created, and there is no need to register local components in vm. The rest remain the same;

Global components use Vue Component ('component name ', component) to create a component;

<body>
    <div id='root'>
        <!-- Authoring component labels -->
        <students/>
    </div>
    <script>
        // Building global variables
        Vue.component('students', {
            data() {
                return {
                    studentName: 'Xiao Ming',
                    studentClass: 'Third grade'
                }
            },
            template: `
                    <div>
                        <span>{{studentName}}</span>
                        <span>{{studentClass}}</span>
                    </div>`
        })
        const vm = new Vue({
            el: '#root',
        })
    </script>
</body>

Nesting of components

One component contains another component, which is called nesting of components; If the student component is nested in the school component:

<body>
    <div id='root'>
        <!-- Authoring component labels -->
        <school></school>
    </div>
    <script>
        // Building local variables
        const student = Vue.extend({
            name: 'student',
            data() {
                return {
                    studentName: 'Xiao Ming',
                    studentClass: 'Third grade'
                }
            },
            template: `
                    <div>
                        <span>{{studentName}}</span>
                        <span>{{studentClass}}</span>
                    </div>`
        })
        const school = Vue.extend({
            data() {
                return {
                    schollName: 'light',
                    schoolClass: 'high school'
                }
            },
            components: {
                student
            },
            // Register the components it contains
            template: `
                    <div>
                        <span>{{schollName}}</span>
                        <span>{{schoolClass}}</span>
                        <student></student>
                    </div>`
        })

        const vm = new Vue({
            el: '#root',
            components: {
                school
            }
        })
    </script>
</body>

The rendered hierarchy is as follows:

All the above explanations are for non single file components. For single file components, it is XXXX vue file, but the browser certainly cannot recognize this type of file. It needs to be parsed with webpack and vue scaffold js file can be recognized and used;

Generally speaking vue files can be named in two ways:

For single word naming files, there are two ways: full lowercase and initial uppercase, such as school Vue and school Vue two;

For multiple word naming files, there are two ways: Dash connection and initial capitalization, such as my school and myschool vue

School. Is recommended Vue and myschool Vue mode

vue files support three types of label writing:

<template>
    <!-- This is the file structure -->
</template>
<script>
    // Here is the code related to component interaction
</script>
<style>
    /*Here is the style of the component */
</style>

The template tag does not change the structure, and there is no template tag after rendering

<template>
    
    <div class="demo">
        <h2>School Name: {{schoolName}}</h2>
        <h2>School address: {{address}}</h2>
        <button @click="showName">Click me to prompt the school name</button>
    </div>
</template>
<script>
    const school = Vue.extend({
        data() {
            return {
                schoolName: 'primary school',
                address: 'here'
            }
        },
        methods: {
            showName() {
                alert(this.schoolName)
            }
        }
    })
</script>
<style>
    .demo {
        color: red;
    }
</style>

Write out another student component:

<template>
    
    <div class="demo">
        <h2>Student Name: {{studentName}}</h2>
        <h2>Age: {{age}}</h2>
    </div>
</template>
<script>
    const student = Vue.extend({
        data() {
            return {
                studentName: 'Zhang San',
                age: 11
            }
        }
    })
</script>
<style>
    .demo {
        color: blue;
    }
</style>

To expose the above two components to other calls, export default is generally used

<script>
    const school = Vue.extend({
        data() {
            return {
                schoolName: 'primary school',
                address: 'here'
            }
        },
        methods: {
            showName() {
                alert(this.schoolName)
            }
        }
    })
    export default school
</script>
<script>
    const student = Vue.extend({
        data() {
            return {
                studentName: 'Zhang San',
                age: 11
            }
        }
    })
    export default student
</script>

It can also be reduced to:

<script>
    export default {
        name: 'school', // Name is generally the same as the file name
        data() {
            return {
                schoolName: 'primary school',
                address: 'here'
            }
        },
        methods: {
            showName() {
                alert(this.schoolName)
            }
        }
    }
</script>
<script>
    export default {
        name: 'student', // Name is generally the same as the file name
        data() {
            return {
                studentName: 'Zhang San',
                age: 11
            }
        }
    }
</script>

Use app Vue component to manage all components, in app The above components are introduced into Vue,

<template>
    <div>
        <!-- Still make sure there is only one root element -->
        <school></school>
        <student></student>
    </div>
</template>
<script>
    import school from '/school'
    import student from '/student'
    export default {
        name: 'app',
        components: {
            school,
            student
        }
    }
</script>
<style>

</style>

Create vm instance (main.js) to manage app components:

import app from '/app.vue'
new Vue({
    el: '#root',
    components: { app }
})

main.js file is also known as the entry file of the project;

Finally, create a container index HTML, associated with vm instance:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>The last step!</title>
</head>

<body>
    <div id="#root">

    </div>
    <script src="js/vue.js"></script>
    <!-- introduce vue.js -->
    <script src="main.js"></script>
    <!-- introduce main.js -->

</body>

</html>

Finally, run the html file and find an error:

Because the browser can't parse the import syntax, you still need to put the project in the scaffold

Topics: Javascript Front-end Vue.js