vue.js组件

有一篇非常棒的关于vue.js的组件的文章,写的特别好,特别清楚,容易理解。链接:上篇:http://www.cnblogs.com/keepfool/p/5625583.html 下篇:http://www.cnblogs.com/keepfool/p/5637834.html

以下是我学习链接所对应的这两篇文章的学习摘要。

1.组件的创建和注册

1.1 创建组件构造器(使用Vue.extend({模板}))

var child = Vue.extend({
    template:'<div>This is my first component!</div>'
})

1.2 注册组件:Vue.component({'组件名',组件构造器名})

Vue.component('my-component',myComponent)

1.3 使用组件

new Vue({
    el:'#app'
});
<div id="app">//组件需挂载到对应的vue实例的挂载范围内
    <my-component></my-component>
</div>

1.4 全局注册

eg:

<div id="example">
    <my-component></my-component>
</div>

<script>
//注册,这种是全局注册
Vue.component('my-component',{
    template:'<div>A component!</div>'
})
//创建根实例
new Vue({
    el:'#example'
})
</script>

渲染为:

<div id="example">
<div>A component!</div>
</div>
效果图

1.5 局部注册

eg:

<div id="example">
    <my-component></my-component>
</div>

<script>
var myComponent = Vue.extend( {
    template: '<div>A component!</div>'
})
new Vue({
    el:'#example',
    components: {
        'my-component':myComponent//用实例选项“components”注册,局部注册
    }
})
</script>
效果图

1.3 全局注册和局部注册区分

在new Vue ()中注册的为局部注册,只能挂到id值与new Vue()中的el值相同的Vue实例,而在new Vue外注册的为全局注册的,可以挂到各个Vue实例。
eg:

<div id="example">
    <my-component></my-component>
</div>
<div id="example-2">
    <my-component></my-component>//将局部注册的组件挂到不对应的组件上,无法正确显示
</div>

<script>
var child = {
    template: '<div>A component!</div>'
}
new Vue({
    el:'#example',
    components: {
        'my-component':child//局部注册的组件
    }
})
</script>
无法正确显示两句话

eg:

<div id="example">
    <my-component></my-component>
</div>
<div id="example-2">
    <my-component></my-component>//将全局注册的组件挂到不同id值的组件上
</div>

<script>
//全局注册
Vue.component('my-component',{
    template:'<div>A component!</div>'
})
//创建根实例
var vm1 = new Vue({
    el:'#example'
})
var vm2 = new Vue({
    el:'#example-2'
})
</script>
正确地显示了两行话

2.父组件和子组件

在一个组件的模板(template)中使用了其他组件,这两个组件之间就构成了父子关系,该组件是父组件,父组件的模板中的组件是子组件。

子组件只能在父组件的template中使用。

  • 创建父组件构造器
  • 创建子组件构造器
  • 注册父组件
  • 注册子组件
  • 使用组件
<div id="app">
    <parent-component>
    </parent-component>
</div>

<script>
//创建父组件构造器,模板中使用了子组件<child-component></child-component>
var parent = Vue.extend({
    template:'<div>This is a parent component!and <child-component></child-component></div>'
})
//创建子组件构造器
var child = Vue.extend({
    template:'<div>This is a child component!</div>'
})
//注册父组件和子组件
Vue.component('child-component',child)
Vue.component('parent-component',parent)
//vue实例
new Vue({
    el:'#app'
});
</script>
运行结果

3.组件注册语法糖:Vue.js简化组件注册的过程

3.1 使用Vue.component()直接创建和注册组件:

// 全局注册,my-component1是标签名称
Vue.component('my-component1',{
    template: '<div>This is the first component!</div>'
})

var vm1 = new Vue({
    el: '#app1'
})

使用这种方式,Vue在背后会自动地调用Vue.extend()。

3.2 在选项对象的components属性中实现局部注册:

var vm2 = new Vue({
    el: '#app2',
    components: {
        // 局部注册,my-component2是标签名称
        'my-component2': {
            template: '<div>This is the second component!</div>'
        },
        // 局部注册,my-component3是标签名称
        'my-component3': {
            template: '<div>This is the third component!</div>'
        }
    }
})

4. 使用script或template标签:分离js代码template中的HTML元素

4.1 使用<script>标签

将原本写在template的内容写在<script type="text/x-template" id="myComponent"></script>标签中,而组件的template的值为<script>标签的“id”值。
Vue.js根据template里面的id值,找到对应的<script>标签,将标签中的HTML作为模板进行编译。

注意:使用<script>标签时,type指定为text/x-template,意在告诉浏览器这不是一段js脚本,浏览器在解析HTML文档时会忽略<script>标签内定义的内容。

<div id="app">
            <my-component></my-component>
 </div>
 <script type="text/x-template" id="myComponent">
      <div>This is a component!</div>
  </script>
<script> 
        Vue.component('my-component',{
            template: '#myComponent'
        })
        
        new Vue({
            el: '#app'
        })        
</script>

4.2 使用<template>标签

<template id="template选项的值">
//这里是原来写在template选项中的HTML
</template>

<div id="app">
      <my-component></my-component>
</div>
<template id="myComponent">
      <div>This is a component!</div>
</template>
<script>
     Vue.component('my-component',{
            template: '#myComponent'
        })
        
        new Vue({
            el: '#app'
        })
</script>

建议使用<script>或<template>标签来定义组件的HTML模板。
这使得HTML代码和JavaScript代码是分离的,便于阅读和维护。

5. 组件的el和data选项

Vue.extend() 或Vue.component()中的data 和el必须是函数。
eg:

Vue.component('my-component', {
    data: function(){
        return {a : 1}
    }
})

6.使用props

6.1基础示例

var vm = new Vue({
    el: '#app',
    data: {
        name: 'keepfool',
        age: 28
    },
    components: {
        'my-component': {
            template: '#myComponent',
            props: ['myName', 'myAge']
        }
    }
})

这个vue实例可以看作'my-component'组件的父组件。要使用父组件的数据例如'data'就要先在子组件中定义props属性。在定义属性的时候用的是驼峰命名。在使用组件时引用props属性的内容时需要转为 kebab-case(短横线隔开)命名。
将父组件数据通过已定义好的props属性传递给子组件:

<div id="app">
    <my-component v-bind:my-name="name" v-bind:my-age="age"></my-component>
//"my-name"对应props的"myName","name"对应父组件的数据"name","my-age"对应props的"myAge","age"对应父组件的数据"age"
</div>

定义子组件的HTML模板:

<template id="myComponent">
    <table>
        <tr>
            <th colspan="2">
                子组件数据
            </th>
        </tr>
        <tr>
            <td>my name</td>
            <td>{{ myName }}</td>//在props属性中定义,将父组件对应的数值传递过来
        </tr>
        <tr>
            <td>my age</td>
            <td>{{ myAge }}</td>////在props属性中定义,将父组件对应的数值传递过来
        </tr>
    </table>
</template>

加上自定义的CSS样式,最终效果图如下:

Paste_Image.png

在父组件中使用子组件时,通过以下语法将数据传递给子组件:
<child-component v-bind:子组件prop="父组件数据属性"></child-component>

6.2 props的绑定类型

6.2.1 单向绑定
  • 修改父组件的数据会影响子组件的数据;
  • 修改子组件的数据不会影响父组件的数据。
6.2.2 双向绑定

可以在使用子组件时,使用.sync显式地指定双向绑定,这使得子组件的数据修改会回传给父组件。

<child-component v-bind:my-name.sync="name" v-bind:my-age.sync="age"></child-component>
6.2.3 单次绑定

可以使用.once显式地指定单次绑定,单次绑定在建立之后不会同步之后的变化,这意味着即使父组件修改了数据,也不会传导给子组件。

<child-component v-bind:my-name.once="name" v-bind:my-age.once="age"></child-component>

6.3 props验证

props: {
    data: Array,
    columns: Array,
    filterKey: String
}

这段代码表示:父组件传递过来的data和columns必须是Array类型,filterKey必须是字符串类型。

7. 解决IE不支持<template>标签

IE不支持<template>标签,所以<template>标签中的内容在IE浏览器中会被显示出来,所以要将<template>的display设置为none。

template{
    display: none;
}

8. 使用slot:内容分发

8.1 单个slot

<div id="app">
    <my-component>
        <h1>Hello vue.js!</h1>
    </my-component>
    <my-component></my-component>
</div>
<template id="temp">
    <h2>this is a component!</h2>
    <slot>slot</slot>
</template>
<script type="text/javascript">
    var vm = new Vue({
        el:'#app',
        components:{
            'my-component':{
                template:'#temp',
            }
        }
    })
</script>

<template>标签中的<slot>,如果在使用该组件的时候,组件中包含了其他内容,就会替换掉<slot>的内容,如果组件没有包含其他内容,<slot>中的内容就会直接显示。组件中包含的内容叫做分发的内容。

Paste_Image.png
8.2 多个slot:指定名字,对应slot
<div id="app">
    <my-component>
    <div slot="slot1">
        <h1>Hello slot1!</h1>
    </div>
    <div slot="slot2">
        <h1>Hello slot2!</h1>
    </div>
    <div slot="slot3">
        <h1>Hello slot3!</h1>
    </div>  
    </my-component>
    <my-component></my-component>
</div>
<template id="temp">
    <h2>this is a component!</h2>
    <slot name="slot1">slot1</slot>
    <slot name="slot2">slot2</slot>
    <slot name="slot3">slot3</slot>
</template>
<script type="text/javascript">
    var vm = new Vue({
        el:'#app',
        components:{
            'my-component':{
                template:'#temp',
            }
        }
    })
</script>
Paste_Image.png
运行结果

9.父子组件之间的访问

9.1父组件访问子组件

9.1.1 $children
父组件.$children[i]
9.1.2 $refs

在子组件上使用v-ref指令,可以给子组件指定一个索引ID:

<template id="parent-component">
    <child-component1 v-ref:cc1></child-component1>
    <child-component2 v-ref:cc2></child-component2>
    <button v-on:click="showChildComponentData">显示子组件的数据</button>
</template>

在父组件中,则通过$refs.索引ID访问子组件的实例:

showChildComponentData: function() {
    alert(this.$refs.cc1.msg);
    alert(this.$refs.cc2.msg);
}

9.2 子组件访问父组件

alert(子组件.$parent.msg)

10.自定义事件

10.1 派发事件$dispatch()

<div id="app">
    <p>Messages: {{ messages | json }}</p>
    <child-component></child-component>
</div>
<template id="child-component">
    <input v-model="msg" />
    <button v-on:click="notify">Dispatch Event</button>
</template>
<script src="js/vue.js"></script>
<script>
    // 注册子组件
    Vue.component('child-component', {
        template: '#child-component',
        data: function() {
            return {
                msg: ''
            }
        },
        methods: {
            notify: function() {
                if (this.msg.trim()) {
                    this.$dispatch('child-msg', this.msg)
                    this.msg = ''
                }
            }
        }
    })
    // 初始化父组件
    new Vue({
        el: '#app',
        data: {
            messages: []
        },
        events: {
            'child-msg': function(msg) {
                this.messages.push(msg)
            }
        }
    })
</script>
  • 子组件的button元素绑定了click事件,该事件指向notify方法
  • 子组件的notify方法在处理时,调用了$dispatch,将事件派发到父组件的child-msg事件,并给该该事件提供了一个msg参数
  • 父组件的events选项中定义了child-msg事件,父组件接收到子组件的派发后,调用child-msg事件。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容

  • 本文章是我最近在公司的一场内部分享的内容。我有个习惯就是每次分享都会先将要分享的内容写成文章。所以这个文集也是用来...
    Awey阅读 9,200评论 4 67
  • 什么是组件 组件(Component)是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装可重用...
    angelwgh阅读 758评论 0 0
  • 这篇笔记主要包含 Vue 2 不同于 Vue 1 或者特有的内容,还有我对于 Vue 1.0 印象不深的内容。关于...
    云之外阅读 4,989评论 0 29
  • 前言 本文由阅读一篇vue.js组件文章学习后笔记http://www.cnblogs.com/keepfool/...
    海娩阅读 737评论 2 2
  • 1、在网站www.phpcms.cn下载安装包。有GBK 和 UTF8两个版本,推荐使用UTF8版本。2、在环境下...
    捔落纏綿阅读 2,032评论 1 0