Home Web Front-end JS Tutorial What are Vue components? How to use Vue components? (code example)

What are Vue components? How to use Vue components? (code example)

Oct 24, 2018 pm 05:38 PM
vue vue component

This article brings you an introduction to what Vue components are? How to use Vue components? (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Introduction to components

  1. The component system divides a large interface into smaller controllable ones. unit.

  2. Components are reusable and maintainable.

  3. The component has strong encapsulation and is easy to use.

  4. In large-scale applications, the interaction between components can be decoupled.

Using Vue components

  • Using global components

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <my-header></my-header>
    </div>


    <script>
        //全局组建的定义
        Vue.component("my-header", {
            template: '<h1>全局组件</h1>'
        });
        var app = new Vue({
            el: '#app',
        });
    </script>

</body>

</html>
Copy after login
  • Use of local components

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <my-header></my-header>
    </div>


    <script>
        //局部组件定义
        var app = new Vue({
            el: '#app',
            components: {
                'my-header': {
                    template: '<h1>局部组件</h1>'
                }
            }
        });
    </script>

</body>

</html>
Copy after login
  • Characteristics of component data

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <my-header></my-header>
        <my-header></my-header>
        <br>
        <my-header1></my-header1>
        <my-header1></my-header1>
    </div>

    <script>
        //组件数据之间不共享,Vue实例中的数据也不能共享给组件,并且组件中的data只能使用函数
        //组件的数据data使用函数的特点是每次点击或操作组件函数会重新执行,这样就不会影响其它组件,通过下面两个例子可以看出
        var data = {
            count: 0
        };
        var app = new Vue({
            el: '#app',
            data: {
                message: "Hello Vue!!!"
            },
            components: {
                'my-header': {
                    template: '<h1 v-on:click="changeCount">{{count}}</h1>',
                    data: function() {
                        return data;
                    },
                    methods: {
                        changeCount: function() {
                            this.count++;
                        }
                    }
                },
                'my-header1': {
                    template: '<div v-on:click="changeCount1">{{count}}</div>',
                    data: function() {
                        return {
                            count: 0
                        };
                    },
                    methods: {
                        changeCount1: function() {
                            this.count++;
                        }
                    }
                }
            }
        });
    </script>

</body>

</html>
Copy after login
  • The relationship between Vue instances and components

The Vue component is actually an extensible Vue instance.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        {{message}}
    </div>

    <script>
        //Vue组件其实是一个可扩展的Vue实例,Vue实例也可以看成是一个组件
        // var app = new Vue({
        //     el: '#app',
        //     template: '<h1>app应用</h1>'
        // });
        //使用继承实现Vue组件
        var myComponent = Vue.extend({
            data: function() {
                return {
                    message: "Hello Vue@@@"
                }
            }
        });
        var vm = new myComponent({
            el: '#app'
        });
    </script>

</body>

</html>
Copy after login
  • The template method of Vue components

  1. \

  2. `

  3. .vue single file

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <my-header></my-header>
        <my-header-1></my-header-1>
        <my-header-2></my-header-2>
        <my-header-3></my-header-3>
    </div>


    <template id="temp">
            <div>
                <p>
                    <ul>
                            <li>1</li>
                            <li>2</li>
                            <li>3</li>
                        </ul>
                    </p>
                </div>
    </template>
    <script type="text/x-template" id="temp1">
        <div>
            <p>
                <ul>
                    <li>1</li>
                    <li>2</li>
                    <li>3</li>
                </ul>
            </p>
        </div>
    </script>
    <script>
        //Vue模版添加方式
        var app = new Vue({
            el: '#app',
            components: {
                'my-header': {
                    template: '<div>\
                                    <p>\
                                        <ul>\
                                            <li>1</li>\
                                            <li>2</li>\
                                            <li>3</li>\
                                        </ul>\
                                    </p>\
                                </div>',
                    data: function() {
                        return {
                            message: "第一项"
                        }
                    }
                },
                'my-header-1': {
                    template: `<div>
                                    <p>
                                        <ul>
                                            <li>1</li>
                                            <li>2</li>
                                            <li>3</li>
                                        </ul>
                                    </p>
                                </div>`,
                },
                'my-header-2': {
                    template: '#temp'
                },
                'my-header-3': {
                    template: '#temp1'
                }

            }
        });
    </script>

</body>

</html>
Copy after login
  • Vue parent component communicates with child components (props)

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <!-- 数据在组件中 -->
        <my-header></my-header>
        <!-- 父组件向子组件传递数据 -->
        <my-header-1 :list="temp_2_list"></my-header-1>
        <!-- 父组件向子组件传递数据不给值 -->
        <my-header-1></my-header-1>

    </div>
    <!-- 数据在组件中的模版 -->
    <template id="temp-1"> 
            <div>
                    <h1>{{message}}</h1>
                    <ul>
                        <li v-for="item in list">{{item}}</li>
                    </ul>
                </div>
    </template>
    <!-- 父组件向子组件传递数据的模版 -->
    <template id="temp-2">
            <div>
                    <h1>{{message}}</h1>
                    <ul>
                        <li v-for="item in list">{{item}}</li>
                    </ul>
                    <my-nav :itemlist = "list"></my-nav>
                </div>
    </template>
    <!-- 子组件向子组件传递数据的模版 -->
    <template id="temp-3">
            <div>
                    <h1>{{message}}</h1>
                    <ul>
                        <li v-for="item in itemlist">{{item}}</li>
                    </ul>
                </div>
    </template>
    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                temp_2_list: ["1", "2", "3"]
            },
            components: {
                //数据在自己组件中的实例
                'my-header': {
                    template: '#temp-1',
                    data: function() {
                        return {
                            list: ["1", "2", "3"],
                            message: "组件中的数据"
                        };
                    }
                },
                //父组件向子组件传递数据
                'my-header-1': {
                    //props: ["list"],
                    template: '#temp-2',
                    data: function() {
                        return {
                            message: "父组件向子组件传递数据"
                        };
                    },
                    //属性的验证与默认值
                    props: {
                        list: {
                            type: Array,
                            default: ["4", "5", "6"]
                        }
                    },
                    //子组件的子组件
                    components: {
                        'my-nav': {
                            template: '#temp-3',
                            data: function() {
                                return {
                                    message: "子组件中的子组件"
                                };
                            },
                            props: ["itemlist"]
                        }
                    }
                }
            }
        });
    </script>

</body>

</html>
Copy after login
  • Child component communicates with parent component (EmitEvents)

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <my-header-1 :list="temp_2_list"></my-header-1>

    </div>
    <!-- 父组件向子组件传递数据的模版 -->
    <template id="temp-2">
        <div>
                <h1>{{message}}</h1>
                <ul>
                    <li v-for="item in list">{{item}}</li>
                </ul>
                <my-nav :itemlist = "list" v-on:change-events="getChildContent"></my-nav>
            </div>
</template>
    <!-- 子组件向子组件传递数据的模版 -->
    <template id="temp-3">
        <div>
                <h1>{{message}}</h1>
                <ul>
                    <li v-for="item in itemlist" v-on:click="getContent">{{item}}</li>
                </ul>
            </div>
</template>

    <script>
        //子组件向父组件传递数据,是发布订阅模式
        var vm = new Vue({
            el: '#app',
            data: {
                temp_2_list: ["1", "2", "3"]
            },
            components: {
                //父组件向子组件传递数据
                'my-header-1': {
                    //props: ["list"],
                    template: '#temp-2',
                    data: function() {
                        return {
                            message: "父组件向子组件传递数据"
                        };
                    },
                    //属性的验证与默认值
                    props: {
                        list: {
                            type: Array,
                            default: ["4", "5", "6"]
                        }
                    },
                    methods: {
                        getChildContent: function(str) {
                            debugger
                            alert(str);
                        }
                    },
                    //子组件的子组件
                    components: {
                        'my-nav': {
                            template: '#temp-3',
                            data: function() {
                                return {
                                    message: "子组件中的子组件"
                                };
                            },
                            props: ["itemlist"],
                            methods: {
                                getContent: function(ev) {
                                    // console.log(this);
                                    // console.log(ev.target.innerHTML);
                                    this.$emit("change-events", ev.target.innerHTML);
                                }
                            }
                        }
                    }
                }
            }
        });
    </script>

</body>

</html>
Copy after login
  • Communication of Vue non-parent-child components

  1. Empty instance With custom events

    1. $emit

    2. $on

  2. Vuex state management

    1. state

    2. mutation

    3. commit

Use of empty instances and custom events (suitable for small projects)

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    <style>
        ul {
            list-style-type: none;
        }
    </style>
</head>

<body>
    <div id="app">
        <my-header-1></my-header-1>
        <my-header-2></my-header-2>

    </div>

    <script>
        //非父子组件通信

        //1.0 使用空实例进行非父子组件通信
        //定义空实例
        //创建步骤是:
        //1、首先定义一个空实例 
        //2、需要给被传递数据的A组件使用$emit绑定自定义事件,并将A组件的数据发布给B组件 
        //3、使用$on订阅A组件发布过来的数据,从而获取数据
        var busVm = new Vue();
        var vm = new Vue({
            el: '#app',
            components: {
                //组件B
                'my-header-1': {
                    template: `<h1>{{message}}</h1>`,
                    data: function() {
                        return {
                            message: "非父子组件通信"
                        };
                    },
                    mounted() {
                        //使用bind(this)修正this
                        busVm.$on("changeEnvents", function(param) {
                            this.message = param;
                        }.bind(this));
                    },
                },
                //组件A
                'my-header-2': {
                    template: `<ul><li @click="getContent" v-for="item in list">{{item}}</li></ul>`,
                    data: function() {
                        return {
                            list: ["第一项", "第二项", "第三项"]
                        };
                    },
                    methods: {
                        getContent: function(ev) {
                            busVm.$emit("changeEnvents", ev.target.innerHTML);
                        }
                    }
                }
            }
        });
    </script>

</body>

</html>
Copy after login

Vuex state management

  • Vue Component content distribution

    • Single tag usage

    ##
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    <style>
        ul {
            list-style-type: none;
        }
    </style>
</head>

<body>
    <div id="app">
        <my-header-1>
            <h1>我是标题</h1>
        </my-header-1>

        <my-header-1>
            <my-header-2></my-header-2>
        </my-header-1>

    </div>

    <script>
        //单插槽<slot></slot>
        var vm = new Vue({
            el: '#app',
            components: {
                'my-header-1': {
                    template: `<div>我是头部:<slot></slot></div>`,

                },
                'my-header-2': {
                    template: `<h1>我是标题</h1>`,
                }
            }
        });
    </script>

</body>

</html>
Copy after login
    • Multiple tags use

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    <style>
        ul {
            list-style-type: none;
        }
    </style>
</head>

<body>
    <div id="app">
       
        <my-header-1>
            <button slot="left">←</button>
            <button slot="right">→</button>
        </my-header-1>

    </div>

    <script>


        //多插槽的使用,则使用name属性来指定要插入的位置
        var vm = new Vue({
            el: '#app',
            components: {
                'my-header-1': {
                    template: `<div><slot name="left"></slot> 我是头部:<slot name="right"></slot></div>`,
                },
                'my-header-2': {
                    template: `<h1>我是标题</h1>`,
                }
            }
        });
    </script>

</body>

</html>
Copy after login
  • Default value

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    <style>
        ul {
            list-style-type: none;
        }
    </style>
</head>

<body>
    <div id="app">

        <my-header-1>
            <button slot="left">←</button>
            <button slot="right">→</button>
        </my-header-1>

    </div>

    <script>
        //多插槽的使用,则使用name属性来指定要插入的位置
        var vm = new Vue({
            el: '#app',
            components: {
                'my-header-1': {
                    template: `<div><slot name="left"></slot> 我是头部:<slot name="right"><button slot="right">+</button></slot></div>`,
                },
                'my-header-2': {
                    template: `<h1>我是标题</h1>`,
                }
            }
        });
    </script>

</body>

</html>
Copy after login
  • Vue component development process

  1. Writing basic HTML and CSS

  2. ##Extraction Component
  3. Data transmission
  4. Content distribution
  5. Add events and methods
  • DOM operation in Vue (using $refs)

  • <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Page Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    </head>
    
    <body>
        <div id="app">
            <my-header-1 :list="temp_2_list"></my-header-1>
    
        </div>
        <!-- 父组件向子组件传递数据的模版,ref特性用于DOM操作,使用this.$refs.row获取添加特性的DOM元素 -->
        <template id="temp-2">
            <div>
                    <h1>{{message}}</h1>
                    <ul >
                        <li  v-for="item in list" v-on:click="updateStyle" style="color:blue" ref="row">{{item}}</li>
                    </ul>
                    
                </div>
          </template>
    
        <script>
            //子组件向父组件传递数据,是发布订阅模式
            var vm = new Vue({
                el: '#app',
                data: {
                    temp_2_list: ["1", "2", "3"]
                },
                components: {
                    //父组件向子组件传递数据
                    'my-header-1': {
                        //props: ["list"],
                        template: '#temp-2',
                        data: function() {
                            return {
                                message: "父组件向子组件传递数据"
                            };
                        },
                        //属性的验证与默认值
                        props: {
                            list: {
                                type: Array,
                                default: ["4", "5", "6"]
                            }
                        },
                        methods: {
                            updateStyle: function(ev) {
                                ev.target.style.color = 'red';
                                // this.$refs.row.style.color = 'red';
                                console.log(this.$refs.row);
                                this.$refs.row.forEach(element => {
                                    console.log(element);
                                    element.style.color = 'red';
                                });
                            }
                        }
                    }
                }
            });
        </script>
    </body>
    </html>
    Copy after login

    The above is the detailed content of What are Vue components? How to use Vue components? (code example). For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

    Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

    How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

    You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

    How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

    The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

    What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

    Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

    How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

    Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

    How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

    There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

    How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

    There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

    How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

    There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

    See all articles