In the process of developing front-end pages, we often encounter scenarios like this:

A particular piece of HTML code might be generic, so I need both this table structure to show here and the same table on another page. Our previous approach was to just paste in the code, which would have done the trick, but ES6 gives us a more elegant way to do it: components.

Generic HTML can be exported as a component and imported directly where it is needed. Doing this in a simple JavaScript file requires a packaging tool, and Vue comes naturally with this.

Component Definition

You can create a Vue component named button-Center with the following command:

<script>
        // Repetitive functionality is defined as a component dash or hump
        // Global registration, which can be used on any Vue object.
        Vue.component('button-center', {// Props can define attributes on tags and pass values back.
            props: ['title'].// Data must be a function to ensure that the count returned is not unique.
            data() {
                return {
                    count: 0}},// A component's template must have a root node
            template: '<div style="border: solid 5px">' +
                '<button @click="clickfun">{{title}}You clicked me {{ count }} times.</button>'
                + '<slot></slot>' + '</div>'.methods: {
                clickfun:function () {
                    this.count++;
                    // Trigger an event with specific parameters
                    this.$emit('clicknow'.this.count); }}});let component = new Vue({
            el: '#components-demo'.data: {},methods: {
                printData:function (e) {
                    console.log(e);
                }
            }
        })
</script>
Copy the code
 <div id="components-demo">
        <! -- Capture the event and pass the argument to printData() -->
        <button-center :title="123" v-on:clicknow="printData">
            <h2>I'm a slot.</h2>
        </button-center>
        <button-center></button-center>
</div>
Copy the code

Application of components in a framework