vue 组件

component

component组件是学习Vue的重点。component是重点!component是重点!component是重点!重要的事情说三遍。

组件与指令之间的区别:

  组件是创建一个新的标签。指令的是已有标签的一个属性。

1.全局组件

  全局组件是在构造器的外面定义的。它没有作用域限制,可以放在多个构造器的作用域中。

  Vue.component('hello',{

    template:`<div style="color:red">我是全局组件</div>`

  })

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

  <div id="pa"><hello></hello></div>

  不同的作用域中都可以出现全局组件。

2.局部组件

  局部组件是在构造器中定义的。局部组件只能在构造器对应的作用域中使用,其他地方是无效的。自己感觉就类似于局部变量。

  var vue=new Vue({

    el:"#app",

    components:{

      "hello":{

        template:`<div style="color:green">我是局部组件</div>`

      }

    }

  })

  <div id="app"><hello></hello></div>      只能在特定的作用域中才有效。

3.props属性设置

  props是设置和获取标签上的属性值。

  定义组件后,定义属性使用props,使用数组形式的属性名称。props:['属性名']。 

  var vue=new Vue({

    el:"#app",

    components:{

      "hello":{

        template:`<div style="color:green">我是局部组件</div>`,

        props:['say']

      }

    }

  })

  <div id="app"><hello say="world"></hello></div>  

   有时属性名有可能是say-hello这种形式的,那么就需要在props中的写法需要采取小驼峰命名法。props:['sayHello']。中间带有-的属性名,都需要采用小驼峰命名法。这个地方是一个坑,要记住,尽量的避免掉坑里。

4.父子组件

  可以在构造器的外部声明组件。

  先声明父组件,在声明的父组件中引用子组件。但是子组件的声明要放在父组件之前。如果放在父组件的后面,那么子组件的内容将不会显示。

  var res={
    template:`<div style="color:green">hello vue!</div>`
  }
  var helloComponent={
    template:`<div>
      <res></res>
      <p>hello world!</p>
    </div>`,
    components:{
      "res":res
    }
  }

 

  

 

posted @ 2018-08-16 16:34  柳如是  阅读(158)  评论(0)    收藏  举报