vue

1 关于组件

组件可以扩展HTML元素,封装可重用的代码。 
注册全局组件: 
Vue.component(tagName,options)的形式。如:

Vue.component('my-component',{
    template:'<div>This is my component</div>'
});
1
2
3
组件注册需要在初始化根实例之前进行,即先注册组件,再初始化Vue实例。对组件进行注册之后,就可以在父实例中使用。

HTML:

<div id="test">
    <my-component></my-component>
</div>
1
2
3
JS:

//注册全局组件
Vue.component('my-component',{
    template:'<div>This is my component</div>'
});
//初始化根实例
var test = new Vue({
    el: '#test',//实例挂载点
});
1
2
3
4
5
6
7
8
渲染结果:

组件局部注册: 
不必在全局注册每个组件。使用组件实例选项注册,可以使组件仅在另一个 实例/组件的作用域中可用。

var child = {
    template: '<div>This is a child component.</div>'
}

var test = new Vue({
    //...
    components: {
        //<my-component>只在父模板中可用
        'my-component':child
    },
});
1
2
3
4
5
6
7
8
9
10
11
2 父子组件

父子组件的关系:通常组件A在它的模板中使用组件B,此时组件A为父组件,组件B为子组件。父子组件应该解耦,组件实例的作用域是孤立的,子组件中不能直接使用父组件的数据。应该使用props传递父组件到子组件的数据,子组件通过events给父组件发消息,以此实现父子组件间的通信。 
如上,在其他组件内部用components声明组件,即为局部注册。在Vue实例中用components注册组件时,可以理解为Vue实例为一个大的父组件,其他任何注册的组件都是子组件。所以在注册组件时,如果要使用Vue实例data中的数据,都要用props传递Vue实例中的数据,让Vue实例的数据在组件中可用。 
还可以用v-bind动态绑定props的值到父组件的数据,父组件数据发生变化时,子组件的数据也相应的变化。

HTML:

<div id="test">
    <template id="testProp">
        <ul>
            <li v-for="book in books">
                <p>{{book.title}}</p>
                <p>{{book.desc}}</p>
                <p>{{book.author}}</p>
            </li>
        </ul>
    <template>
    <test-prop :book-list = "books"></test-prop>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
JS:

var TestProp = Vue.extend({
    template:'#testProp',
    props: ['book-list']
});
var test = new Vue({
    el: '#test',
    data: function(){
        return {
            books: [
                {
                    title: 'title1',
                    desc: 'desc1',
                    author: 'author1'
                },
                {
                    title: 'title2',
                    desc: 'desc2',
                    author: 'author2'
                },
                {
                    title: 'title3',
                    desc: 'desc3',
                    author: 'author3'
                },
            ],
        }
    },
    components:{
        'test-prop': TestProp,
    },
});
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值