vue 组件-component

组件-component

1.什么是组件

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

2.定义组件的方式

方式1:先创建组件的构造器,然后由构造器创建组件
    /* 方式1:先创建组件的构造器,再由构造器创建组件 */
    var myComponent = Vue.extend({
     
        template:"

hello vue!

"
}) Vue.component("hello",myComponent)
方式2:直接创建组件
    /* 方式2:直接创建组件 */
    Vue.component("world",{
     
        template:"

hello world!

"
})

3.组件的分类

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

    var vm = Vue({
     
        el:"#app",
        data:{
     
            name:"yiyi"
        },
        components:{
                 // 局部组件记得加s,为:components
            "hello":{
     
                template:"

{ {name}}

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

    Vue.component("hello",{
     
        template:"

{ {name}}

"
, data:function(){ return { name:"yang" } } })

4.组件引用模版

组件引用模版可以使用一个特定的标签来引入,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"]
                    }
                }
            }
        }
    })


你可能感兴趣的:(vue2.0)