8-Vue组件基础

组件是可复用的 Vue 实例,且带有一个名字:在这个例子中是 <button-counter>。我们可以在一个通过 new Vue 创建的 Vue 根实例中,把这个组件作为自定义元素来使用:

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title>组件基础</title>
        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    </head>
        <div id="components-demo">
            <!-- 通过 new Vue 创建的 Vue 根实例中,把这个组件作为自定义元素来使用 -->
            <!--组件的复用-->
            <button-counter></button-counter>
            <button-counter></button-counter>
            <button-counter></button-counter>
        </div>
        <!-- 注意当点击按钮时,每个组件都会各自独立维护它的 count。因为你每用一次组件,就会有一个它的新实例被创建。 -->
    <body>
        
    </body>
    <script type="text/javascript" src="js/vue.js"></script>
    <script>
        // 组件是可复用的 Vue 实例,定义一个名为 button-counter 的新组件
        Vue.component('button-counter',{
            //一个组件的 data 选项必须是一个函数
            //因此每个实例可以维护一份被返回对象的独立的拷贝
            data: function(){
                return {
                    count: 0
                }
            },
            template: `
                <button @click="count++">您点击了{{count}}次</button>
            `
        })
        new Vue({
            el: '#components-demo'
        })
    </script>
</html>

组件能够复用的原因:
每个组件都会各自独立维护它的 count。因为你每用一次组件,就会有一个它的新实例被创建。

注意:一个组件的 data 选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title>prop</title>
        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    </head>
        <div id="components-prop">
            <blog-post v-for="post in posts" v-bind:post="post"></blog-post>
        </div>
    <body>
        
    </body>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script type="text/javascript">
        // 注册组件,传递prop属性
        Vue.component('blog-post', { 
            template: "<p>{{post.id}}.{{post.title}}</p>", 
            props: ['post'], 
        })
        new Vue({
            el: '#components-prop',
            data: {
                posts: [
                    { id: 1, title: 'My journey with Vue' },
                    { id: 2, title: 'Blogging with Vue' },
                    { id: 3, title: 'Why Vue is so fun' }
                ]
            }
        })
    </script>
</html>

如上所示,你会发现我们可以使用 v-bind 来动态传递 prop。这在你一开始不清楚要渲染的具体内容,比如从一个 API 获取博文列表的时候,是非常有用的。

单个根元素

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title>prop</title>
        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    </head>
        <div id="components-prop">
            <blog-post v-for="post in posts" v-bind:key="post.id" v-bind:post="post"></blog-post>
        </div>
    <body>
        
    </body>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script type="text/javascript">
        // 注册组件,传递prop属性   
        Vue.component('blog-post', { 
            props: ['post'],
            // 每个组件必须只有一个根元素,这里外面必须套一层div,不然模板div里面的内容不会显示 
            template: `
                <div class="blog-post">
                    <h3 v-text="post.title"></h3>
                    <div v-html="post.id + '.' + post.content"></div>
                </div>    
            `, 
        })
        new Vue({
            el: '#components-prop',
            data: {
                posts: [
                    { id: 1, title: 'My journey with Vue',content: 'My journey with Vue,My journey with Vue' },
                    { id: 2, title: 'Blogging with Vue',content: 'Blogging with Vue,Blogging with Vue' },
                    { id: 3, title: 'Why Vue is so fun',content: 'Why Vue is so funWhy Vue is so fun' }
                ]
            }
        })
    </script>
</html>

监听子组件事件

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title>prop</title>
        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    </head>
        <div id="components-prop" :style="{ fontSize: postFontSize + 'em' }">
            <!-- 父级组件通过 v-on 监听子组件实例的任意自定义事件,这里是监听子组件的change-text自定义事件 -->
            <blog-post v-for="post in posts" v-bind:key="post.id" v-bind:post="post" v-on:change-text="postFontSize+=0.1"></blog-post>
        </div>
    <body>
        
    </body>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script type="text/javascript">
        // 注册组件,传递prop属性   
        Vue.component('blog-post', { 
            props: ['post'],
            // 每个组件必须只有一个根元素,这里外面必须套一层div,不然模板div里面的内容不会显示 
            // 同时子组件可以通过调用内建的 $emit 方法 并传入事件名称(这里是change-text)来触发这个事件
            template: `
                <div class="blog-post">
                    <h3 v-text="post.title"></h3>
                    <button v-on:click="$emit('change-text')">字体变大</button>
                    <div v-html="post.id + '.' + post.content"></div>
                </div>    
            `, 
        })
        new Vue({
            el: '#components-prop',
            data: {
                posts: [
                    { id: 1, title: 'My journey with Vue',content: 'My journey with Vue,My journey with Vue' },
                    { id: 2, title: 'Blogging with Vue',content: 'Blogging with Vue,Blogging with Vue' },
                    { id: 3, title: 'Why Vue is so fun',content: 'Why Vue is so funWhy Vue is so fun' }
                ],
                // 在其父组件中,我们可以通过添加一个 postFontSize 数据属性来支持这个功能
                postFontSize: 1
            }
        })
    </script>
</html>

当点击这个按钮时,我们需要告诉父级组件放大所有博文的文本。幸好 Vue 实例提供了一个自定义事件的系统来解决这个问题。父级组件可以像处理 native DOM 事件一样通过 v-on 监听子组件实例的任意事件:同时子组件可以通过调用内建的 $emit 方法 并传入事件名称来触发一个事件:
有了这个 v-on:enlarge-text="postFontSize += 0.1" 监听器,父级组件就会接收该事件并更新 postFontSize 的值。

使用事件抛出一个值

有的时候用一个事件来抛出一个特定的值是非常有用的。例如我们可能想让 <blog-post> 组件决定它的文本要放大多少。这时可以使用 $emit 的第二个参数来提供这个值:

<button v-on:click="$emit('change-text',0.1)">字体变大</button>

然后当在父级组件监听这个事件的时候,我们可以通过 $event 访问到被抛出的这个值:

<blog-post v-for="post in posts" v-bind:key="post.id" v-bind:post="post" v-on:change-text="postFontSize+=$event"></blog-post>

完整demo如下:

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title>prop</title>
        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    </head>
        <div id="components-prop" :style="{ fontSize: postFontSize + 'em' }">
            <!-- 父级组件通过 v-on 监听子组件实例的任意自定义事件,这里是监听子组件的change-text自定义事件 -->
            <blog-post v-for="post in posts" v-bind:key="post.id" v-bind:post="post" v-on:change-text="postFontSize+=$event"></blog-post>
        </div>
    <body>
        
    </body>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script type="text/javascript">
        // 注册组件,传递prop属性   
        Vue.component('blog-post', { 
            props: ['post'],
            // 每个组件必须只有一个根元素,这里外面必须套一层div,不然模板div里面的内容不会显示 
            // 同时子组件可以通过调用内建的 $emit 方法 并传入事件名称(这里是change-text)来触发这个事件
            template: `
                <div class="blog-post">
                    <h3 v-text="post.title"></h3>
                    <button v-on:click="$emit('change-text',0.1)">字体变大</button>
                    <div v-html="post.id + '.' + post.content"></div>
                </div>    
            `, 
        })
        new Vue({
            el: '#components-prop',
            data: {
                posts: [
                    { id: 1, title: 'My journey with Vue',content: 'My journey with Vue,My journey with Vue' },
                    { id: 2, title: 'Blogging with Vue',content: 'Blogging with Vue,Blogging with Vue' },
                    { id: 3, title: 'Why Vue is so fun',content: 'Why Vue is so funWhy Vue is so fun' }
                ],
                // 在其父组件中,我们可以通过添加一个 postFontSize 数据属性来支持这个功能
                postFontSize: 1
            }
        })
    </script>
</html>

或者,如果这个事件处理函数是一个方法:那么这个值将会作为第一个参数传入这个方法

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title>prop</title>
        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    </head>
        <div id="components-prop" :style="{ fontSize: postFontSize + 'em' }">
            <!-- 父级组件通过 v-on 监听子组件实例的任意自定义事件,这里是监听子组件的change-text自定义事件 -->
            <blog-post v-for="post in posts" v-bind:key="post.id" v-bind:post="post" v-on:change-text="onChangeText"></blog-post>
        </div>
    <body>
        
    </body>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script type="text/javascript">
        // 注册组件,传递prop属性   
        Vue.component('blog-post', { 
            props: ['post'],
            // 每个组件必须只有一个根元素,这里外面必须套一层div,不然模板div里面的内容不会显示 
            template: `
                <div class="blog-post">
                    <h3 v-text="post.title"></h3>
                    <button v-on:click="$emit('change-text',0.1)">字体变大</button>
                    <div v-html="post.id + '.' + post.content"></div>
                </div>    
            `, 
        })
        new Vue({
            el: '#components-prop',
            methods: {
                onChangeText: function (enlargeAmount) {
                    this.postFontSize += enlargeAmount
                }
            },
            data: {
                posts: [
                    { id: 1, title: 'My journey with Vue',content: 'My journey with Vue,My journey with Vue' },
                    { id: 2, title: 'Blogging with Vue',content: 'Blogging with Vue,Blogging with Vue' },
                    { id: 3, title: 'Why Vue is so fun',content: 'Why Vue is so funWhy Vue is so fun' }
                ],
                // 在其父组件中,我们可以通过添加一个 postFontSize 数据属性来支持这个功能
                postFontSize: 1
            }
        })
    </script>
</html>

在组件上使用 v-model

v-model本身就是一个利用叫value的prop和叫input的自定义事件。所以完全可以自己写,因为单选,复选等类型的输入控键,会使用value特性用于其他目的。

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title>在组件上模拟v-model</title>
        <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    </head>
        <div id="app">
            <custom-input v-bind:value="searchText" v-on:input="searchText=$event"></custom-input>
            <p>{{ searchText}}</p>
        </div>
        <!-- 
            1. v-bind:value='searchText'
            绑定: 初始化data的数据对象和Prop特性value
            数据流动:从外到内。外部传入的数据可以被Vue实例得到,存在自定义的Props: value特性中。

            2. v-on:input自定义='searchText = $event '
            监听: input事件。自定义的事件。非原生HTMLDOM-input。
            数据流动:从内到外。Vue实例的value特性的值,被赋予数据对象searchText。
        -->
    <body>
        
    </body>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script type="text/javascript">
        // 注册组件,传递prop属性   
        Vue.component('custom-input', {
        props: ['value'],
        template: `
            <input v-bind:value="value" v-on:input="$emit('input', $event.target.value)">
        `
        })
        new Vue({
            el: '#app',
            data: {
                searchText: "模拟v-model"
            },
        })
        /* 
        1. <input>中的v-bind:value="value"
        绑定: input元素的value特性和组件的prop特性value
        数据流动:从外到内。外部传入的数据被prop value特性得到,然后再被Vue实例的<input>的value特性得到。

        2. <input>中的v-on:input="$emit('input', $event.target.value)"
        监听: input事件。这是原生的HTMLDOM事件。
        数据流动:从内到外。当用户在输入框输入任意字符后,后台监听到input事件,然后执行$emit这个实例方法。
        $emit(eventName, 参数),这个实例方法会触发当前实例上的事件'input',并发送参数。
        实例上的v-on监听到了事件'input',执行一个内联语句。参数被赋予searchText对象。
        */
    </script>
</html>

关于event.target.valueevent是触发的事件,这里是在输入框输入的动作。

$event.target是这个动作作用在哪个元素上。target特性返回被事件激活的元素。这里是输入框input元素。

value指的是input中的value特性,即输入的内容。

通过插槽分发内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <alert-box>
            Something bad happened.
        </alert-box>
    </div>
    <script src="js/vue.js"></script>
    <script>
        Vue.component('alert-box', {
        template: `
            <div class="demo-alert-box">
            <strong>Error!</strong>
            <slot></slot>
            </div>
        `
        });
        var app = new Vue({
            el: '#app'
        })
    </script>
</body>
</html>

动态组件

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>动态组件Tab</title>
    <style>
      .tab-button {padding: 6px 10px; border-top-left-radius: 3px; border-top-right-radius: 3px; border: 1px solid #ccc; cursor: pointer; background: #f0f0f0; margin-bottom: -1px; margin-right: -1px; }
      .tab-button:hover {background: #e0e0e0; }
      .tab-button.active {background: #e0e0e0; }
      .tab {border: 1px solid #ccc; padding: 10px; }
    </style>
  </head>
  <body>
    <div id="dynamic-component-demo" class="demo">
      <button v-for="tab in tabs" v-bind:key="tab" v-bind:class="['tab-button', { active: currentTab === tab }]" v-on:click="currentTab = tab">
        {{ tab }}
      </button>

      <component v-bind:is="currentTabComponent" class="tab"></component>
    </div>
    <script src="js/vue.js"></script>
    <script>
      Vue.component("tab-home", {template: "<div>Home component</div>"});
      Vue.component("tab-posts", {template: "<div>Posts component</div>"});
      Vue.component("tab-archive", {template: "<div>Archive component</div>"});

      new Vue({
        el: "#dynamic-component-demo",
        data: {
          currentTab: "Home",
          tabs: ["Home", "Posts", "Archive"]
        },
        computed: {
          currentTabComponent: function() {
            return "tab-" + this.currentTab.toLowerCase();
          }
        }
      });
    </script>
  </body>
</html>

上述内容可以通过 Vue 的 <component> 元素加一个特殊的 is 特性来实现:

解析 DOM 模板时的注意事项

有些 HTML 元素,诸如 <ul>、<ol>、<table> 和 <select>,对于哪些元素可以出现在其内部是有严格限制的。而有些元素,诸如 <li>、<tr> 和 <option>,只能出现在其它某些特定的元素内部。

这会导致我们使用这些有约束条件的元素时遇到一些问题。例如:

<table>
  <blog-post-row></blog-post-row>
</table>

这个自定义组件 <blog-post-row> 会被作为无效的内容提升到外部,并导致最终渲染结果出错。幸好这个特殊的 is 特性给了我们一个变通的办法:

<table>
  <tr is="blog-post-row"></tr>
</table>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 组件(Component)是Vue.js最核心的功能,也是整个架构设计最精彩的地方,当然也是最难掌握的。...
    六个周阅读 5,652评论 0 32
  • 主要还是自己看的,所有内容来自官方文档。 介绍 Vue.js 是什么 Vue (读音 /vjuː/,类似于 vie...
    Leonzai阅读 3,381评论 0 25
  • Vue 实例 属性和方法 每个 Vue 实例都会代理其 data 对象里所有的属性:var data = { a:...
    云之外阅读 2,244评论 0 6
  • 什么是组件? 组件 (Component) 是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装...
    youins阅读 9,528评论 0 13
  • vue概述 在官方文档中,有一句话对Vue的定位说的很明确:Vue.js 的核心是一个允许采用简洁的模板语法来声明...
    li4065阅读 7,275评论 0 25