zoukankan      html  css  js  c++  java
  • Vue 创建组件的两种方法

    地址:https://blog.csdn.net/cofecode/article/details/74634301

    创建组件的两种方法

    1.全局注册 
    2.局部注册

    var child=Vue.extend({})
    
    var parent=Vue.extend({})
    • 1
    • 2
    • 3

    Vue.extend() 全局方法 生成构造器,创建子类

    使用基础 Vue 构造器,创建一个“子类”。

    这样写非常繁琐。于是vue进行了简化

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

    Vue.component(id,options) 全局方法 用来注册全局组件

    id 是string类型,即是注册组件的名称 
    options 是个对象

    // 全局注册,my-component1是标签名称
    Vue.component('my-component1',{
        template: '<div>This is the first component!</div>'
    })
    
    var vm1 = new Vue({
        el: '#app1'
    })
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    Vue.component()的第1个参数是标签名称,第2个参数是一个选项对象,使用选项对象的template属性定义组件模板。 
    使用这种方式,Vue在背后会自动地调用Vue.extend()。

    在选项对象的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>'
            }
        }
    })
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    ==局部注册都放在选项对象中创建==

    注意:这里是components,里面可以定义多个组件。

    简化后是这样的写法

    <body>
        <div id='box'>      
            <parent>        
            </parent>
        </div>
    
        <script src='js/vue.js'></script>
        <script>
    
            Vue.component('parent',{
                template:`<div><h1>我是父组件</h1><child></child></div>`,
                    components:{
                    'child':{
                        template:`<h1>我是子组件</h1>`
                    }
                }
            })
    
    
            new Vue({
                el:'#box'
            })
    
        </script>
    </body>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    注册一个parent的父组件。然后在父组件的选项对象中注册一个child的子组件。将子组件child的标签写到父组件parent的template里面。

    页面上的样式结构就是

    <div>
        <h1>我是父组件</h1>
        <h1>我是子组件</h1>
    </div>
    • 1
    • 2
    • 3
    • 4

    注意:用局部注册的子组件不能单独直接使用!

    标签挂在div里,会报错

    <div id='box'>      
        <child></child>
    </div>
    
    结果会报错
  • 相关阅读:
    java算法小例子
    Spring Boot学习笔记---Spring Boot 基础及使用idea搭建项目
    SpringBoot核心特性之组件自动装配
    spring cloud eureka注册原理-注册失败填坑
    红黑树存在的合理性
    IO模型(epoll)--详解-03
    IO模型(epoll)--详解-02
    IO模型(epoll)--详解-01
    JVM-类加载原理
    并发之原子性、可见性、有序性
  • 原文地址:https://www.cnblogs.com/bydzhangxiaowei/p/9104274.html
Copyright © 2011-2022 走看看