Vue.js学习及总结——组件系统

先来看一个简单的实例:

html

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

js

创建模板
var MyComponent = Vue.extend({
    template: '<div>A good idea!</div>'
});
//注册一下  就是申明 绑定一下
Vue.component('my-component',MyComponent);
//创建实例  就是绑定到父级 div#component
new Vue({
  el: '#component'
});
接着看 内部注册一个模板: 内部模板只能使用在父级的模板内(即:template 的字符串中) 下面代码  ****** 标注

html

<div id="ex000">
    <my-component msg="hello"></my-component>
</div>

 js

//局部注册
var show = Vue.extend({
    template: '<div>sssssssssssssssssssssssssssssssssss</div>'
});

//全局注册
//定义
var showss = Vue.extend({
    //模板 
    template: '<div>{{ msg }} {{ privateMsg }} <show-s></show-s></div>', // ******
    //参数  
    //props: {
    //    msg: ''
    //},
    props: ['msg'],
    //数据
    data: function () {
        return {
            privateMsg: '2222222222222'
        }
    },
    //内部的模板 使用components 进行扩展及调用
    components: {
        //连接内部模板  调用局部模板:show
        'show-s': show
    }

});

//注册
Vue.component('my-component', showss);

//创建实例
var ex000 = new Vue({
    el: '#ex000'
});

 效果:

再来看看 父级与子级间的通讯

html

<div id="demo-2">
    <input v-model="parentMsg">
    <br>
    <child v-bind:my-message="parentMsg"></child>
</div>
 

 js

var child = Vue.extend({
    props: ['myMessage'],
    template: '<span>{{myMessage}}</span>'
});
new Vue({
    el: '#demo-2',
    data: {
        parentMsg: 'Message from parent'
    },
    components: {
       //不带引号('child')则是注册的是子级 可以在页面直接使用  带引号则是内部注册 只能在内部的template中使用
        child: child
    }
});

//components还可以这么写
components: {
   child: {
        props: {               // or  props: ['myMessage']
          'myMessage': ''    
        }
        template: '<span>{{ myMessage }}</span>'
    }
}


效果:  

 

 自定义 :

html

<!-- 子组件模板 -->
<template id="child-template">
  <input v-model="msg">
  <button v-on:click="notify">Dispatch Event</button>
</template>

<!-- 父组件模板 -->
<div id="events-example">
  <p>Messages: {{ messages | json }}</p>
  <child></child>
// <child v-on:child-msg="handleIt"></child>
</div>

 js

// 注册子组件
// 将当前消息派发出去
Vue.component('child', {
    template: '#child-template',
    data: function () {
        return { msg: 'hello' }
    },
    methods: {
        notify: function () {
            if (this.msg.trim()) {
                this.$dispatch('child-msg', this.msg);  // 触发child-msg事件
                this.msg = '';
            }
        }
    }
});

// 启动父组件
// 将收到消息时将事件推入一个数组
var parent = new Vue({
    el: '#events-example',
    data: {
        messages: []
    },
    // 在创建实例时 `events` 选项简单地调用 `$on`
    events: {
        'child-msg': function (msg) {  // 监听到 child-msg事件
            // 事件回调内的 `this` 自动绑定到注册它的实例上
            this.messages.push(msg);  // messages改变自动修改html内容
        }
    }
});

 效果:


 

猜你喜欢

转载自dingliang-321.iteye.com/blog/2265730