组件之全局局部注册父组件子组件

组件可以扩展HTML元素,封装可重用的HTML代码,我们可以将组件看作自定义的HTML元素,组件系统提供了一种抽象,让我们可以使用独立可复用的小组件来构建大型应用。

全局注册

<!DOCTYPE html>
<html>
    <body>
        <div id="app">
            <!-- 3. #app是Vue实例挂载的元素,应该在挂载元素范围内使用组件-->
            <the-component></the-component>
        </div>
    </body>
    <script src="js/vue.js"></script>
    <script>

        // 1.创建一个组件构造器
        var myComponent = Vue.extend({
            template: '<div> my first component!</div>'
        })

        // 2.注册组件,并指定组件的标签,组件的HTML标签为<the-component> 
        Vue.component('the-component', myComponent)

        new Vue({
            el: '#app'
        });

    </script>
</html>

分析:
1:Vue.extend()是Vue构造器的扩展,调用Vue.extend()构建的是一个组件构造器,而不是一个具体的组件实例,它里面的选项对象的template属性用于定义组件要渲染的HTML。

2:Vue.component()注册组件时,需要提供2个参数,第一个参数是组件的标签,第二个是组件构造器,它调用了组件构造器myCononent,创建一个组件实例

3:组件应该挂载在某个Vue实例下

new Vue({
  el: '#app'
})

这段代码必须要有,表示挂载在#app元素上,否则不会生效。

局部注册

<script>

        // 1.创建一个组件构造器
        var myComponent = Vue.extend({
            template: '<div> my first2 component!</div>'
        })

        new Vue({
            el: '#app',
            components: {
                // 2. 将myComponent组件注册到Vue实例下
                'the-component' : myComponent
            }
        });

    </script>

父组件和子组件:可以在组件中定义并使用其他组件,构造父子组件关系

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <!-- 子组件模板 -->
    <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>
    </div>
  </body>
  <script src="http://cdn.bootcss.com/vue/1.0.0-csp/vue.js"></script>
  <script>
  // 注册子组件
  // 将当前消息派发出去
  Vue.component('child', {
    template: '#child-template',
    data: function () {
      return { msg: 'hello' }
    },
    methods: {
      notify: function () {
        if (this.msg.trim()) {
          this.$dispatch('child-msg', this.msg)
          this.msg = ''
        }
      }
    }
  })

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

  </script>
</html>

参考博客:https://www.cnblogs.com/wj204/p/5923045.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值