vue 组件-component

组件-component

1.什么是组件

组件(component)是vue.js最强大的功能之一,组件可以扩展HTML元素,封装可重用的代码
组件是自定义元素(对象)

2.定义组件的方式

方式1:先创建组件的构造器,然后由构造器创建组件
    /* 方式1:先创建组件的构造器,再由构造器创建组件 */
    var myComponent = Vue.extend({
        template:"<h3>hello vue!</h3>"
    })
    Vue.component("hello",myComponent)
方式2:直接创建组件
    /* 方式2:直接创建组件 */
    Vue.component("world",{
        template:"<h3>hello world!</h3>"            
    })

3.组件的分类

1).局部组件
    html调用方法:<hello></hello>

    var vm = Vue({
        el:"#app",
        data:{
            name:"yiyi"
        },
        components:{            // 局部组件记得加s,为:components
            "hello":{
                template:"<p>{{name}}</p>",     // 这里的name无法访问到根组件vm内的data数据
                data:function(){        // 局部组件内存储数据必须是一个函数
                    return {
                        name:"yang"
                    }
                }
            }
        }
    })
2).全局组件
全局组件为:Vue.component("组件名",{
                template:"组件标签内容",
                data:function(){            // 这里必须是一个函数,用return返回存储的数据
                    return 数据
                }
            })
    html调用方法:<hello></hello>

    Vue.component("hello",{
        template:"<p>{{name}}</p>",
        data:function(){
            return {
                name:"yang"
            }
        }
    })

4.组件引用模版

组件引用模版可以使用一个特定的标签<template></template>来引入,template标签子元素,只能有一个
    html部分:
    <hello></hello>
    <template id="myHello">
        <div>       // template子元素只能有一个
            <p>{{msg}}</p>
            <ul>
                <li v-for="i in arr"></li>
            </ul>
        </div>
    </template>

    js部分:
    var vm = Vue({
        el:"#app",
        component:{
            "hello":{
                template:"#myHello",        // 使用模版ID引入
                data:function(){
                    return {                // 储存的数据
                        msg:"hello vue!",
                        arr:["hehe","haha","heihei"]
                    }
                }
            }
        }
    })


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值