Vue组件理解

来源:互联网 发布:软件测试原佩腾 编辑:程序博客网 时间:2024/04/18 20:25

1 关于组件

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

Vue.component('my-component',{    template:'<div>This is my component</div>'});

组件注册需要在初始化根实例之前进行,即先注册组件,再初始化Vue实例。对组件进行注册之后,就可以在父实例中使用。

HTML:

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

JS:

//注册全局组件Vue.component('my-component',{    template:'<div>This is my component</div>'});//初始化根实例var test = new Vue({    el: '#test',//实例挂载点});

渲染结果:

渲染结果:

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

var child = {    template: '<div>This is a child component.</div>'}var test = new Vue({    //...    components: {        //<my-component>只在父模板中可用        'my-component':child    },});

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>

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