vue组件化开发(component)

组件说明

  • Vuejs通过Vue.extend(options) 方法来扩展组件的使用
  • options参数和 Vue(options) 的options参数几乎是一致的
  • new Vue出来的 ViewModel( 视图模型 ) 也是一个组件,我们称之为 ‘根实例组件’ ,叫 ‘Root’ 组件
  • Vue中组件的表现形式是类似于标签的,要想像标签一样使用,就必须得符合 h5 的规则,也就是必须要进行组件的注册
  • 组件的注册有两种形式:全局注册局部注册

全局注册

  1. 格式:
    Vue.component(组件的名称,组件的配置项)

  2. 命名规则:
    1)Hello
    2)my-button

  3. 使用:


//1. 组件的配置项
const Hello = Vue.extend({
    //组件中的模板需要使用一个叫做template的配置项来表示
    template: '<div> Hello component!!! </div>'
})
// 2. 组件的注册
Vue.component( 'Hello', Hello )
//上面两步可以合并成一步

Vue.component('Hello',{
    template: '<div> Hello component!!! </div>'
})

//组件必须先注册再使用(一定要先第二步再第三步)
// 3. 组件的使用
new Vue({
    el: '#app'
})

局部注册(在根实例配置项的components中进行注册)

new Vue({
    el: '#app',
    components: {
        'Hello': {
            template: `
                <h3> hello 局部注册
                <p> 1902 </p> </h3>
                `
            }
        }
})

template模板分离

component中template的html代码分离到html中,使用template标签+id实现挂载


<template id="hello">
    <div>
        <h3> hello 预祝端午节happy </h3>
    </div>
</template>

  • template标签下的标签只能有一个(
    template组件中有且仅有一个根元素)

new Vue({
    el: '#app',
    components: {
        'Hello': {
        template: '#hello'
        }
    }
})


组件使用时的直接子元素规则

  • 一些html标签直接规定了直接子元素:如:ul li ol li table tr td dl dt dd select option
  • 将组件直接写入时会出现问题
  • 解决:在直接子元素身上通过 is 属性来绑定 组件

<table>
    <tr>
        <td>1</td>  
        <td>2</td>
        <td>3</td>
    </tr>
    <!-- <Hello></Hello> 这么写有问题-->
    <tr is = "Hello"></tr>
</table>


组件的嵌套


<div id="app">
    <Father></Father>
</div>

<template id="father">
    <div>
        <h3> father </h3>
        <hr>
        <Son></Son>
</div>
</template>

<template id="son">
    <h3> son </h3>
</template>

全局

Vue.component('Father',{
    template: '#father'
})
Vue.component('Son',{
    template: '#son'
})
new Vue({
    el: '#app',
})

局部

new Vue({
    el: '#app',
    components: {
        'Father': {
            template: '#father',
            components: {
                'Son': {
                    template: '#son'
                }
            }
        }
    }
})

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值