>  기사  >  웹 프론트엔드  >  Vue 구성요소란 무엇입니까? Vue 컴포넌트를 사용하는 방법은 무엇입니까? (코드 예)

Vue 구성요소란 무엇입니까? Vue 컴포넌트를 사용하는 방법은 무엇입니까? (코드 예)

青灯夜游
青灯夜游앞으로
2018-10-24 17:38:372280검색

이 기사에서는 Vue 구성 요소가 무엇인지 소개합니다. Vue 컴포넌트를 사용하는 방법은 무엇입니까? (코드 예). 도움이 필요한 친구들이 참고할 수 있기를 바랍니다.

컴포넌트 소개

  1. 컴포넌트 시스템은 대규모 인터페이스를 제어 가능한 작은 단위로 나눕니다.

  2. 구성 요소는 재사용 및 유지 관리가 가능합니다.

  3. 구성 요소는 강력한 캡슐화로 되어 있어 사용하기 쉽습니다.

  4. 대규모 애플리케이션에서는 구성 요소 간의 상호 작용이 분리될 수 있습니다.

Vue 구성 요소 사용

  • 전역 구성 요소 사용

<!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>
  • 로컬 구성 요소 사용

<!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>
  • 컴포넌트 데이터의 특징

<!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>
  • Vue 인스턴스와 구성 요소 간의 관계

Vue 구성 요소는 실제로 확장 가능한 Vue 인스턴스입니다.

<!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>
  • Vue 구성 요소의 템플릿 방법

  1. `

  2. <스크립트 type = "Text/X-Template" & GT; & LT;/Script & GT; 상위 구성 요소(EmitEvents)와 통신합니다

  3. <!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>
    Vue 비상위 구성 요소
빈 인스턴스 및 사용자 정의 이벤트
  • $emit

    $on
  • Vuex 상태 관리
  1. state

    1. 돌연변이

    2. 커밋

  2. 빈 인스턴스 및 사용자 정의 이벤트 사용(소규모 프로젝트에 적합)

    <!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>
    Vuex 상태 관리
    1. Vue 구성 요소 콘텐츠 배포
    2. 단일<슬롯> 태그 사용

    <!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>

다중 태그 사용

  • <!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>
    기본값
    • <!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>

    Vue 구성 요소 개발 프로세스
    • 기본 HTML 및 CSS 작성
    구성요소 추출 중
  • 데이터 전송
  • 콘텐츠 배포

  • 이벤트 및 메소드 추가
  1. Vue에서 DOM 작업($refs 사용)

  2. rrre 에

위 내용은 Vue 구성요소란 무엇입니까? Vue 컴포넌트를 사용하는 방법은 무엇입니까? (코드 예)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 cnblogs.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제