美文网首页
Vue 组件

Vue 组件

作者: lyp82nkl | 来源:发表于2019-07-10 21:49 被阅读0次

对组件的理解 :

组件 (Component) 是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装可重用的代码。在较高层面上,组件是自定义元素,Vue.js 的编译器为它添加特殊功能。在有些情况下,组件也可以表现为用 is 特性进行了扩展的原生 HTML 元素。所有的 Vue 组件同时也都是 Vue 的实例,所以可接受相同的选项对象 (除了一些根级特有的选项) 并提供相同的生命周期钩子。

组件的好处:

  • 提高开发效率
  • 方便重复使用
  • 简化调试步骤
  • 提高整个项目的可维护性
  • 便于协同开发

组件的使用方法:

全局注册

全局化组件就是在构造器的外部用Vue.component来注册一个组件

<div class="app">
    <my-component></my-component> 
</div>

Vue.component('my-component',{ 
template:'<div>我是组件的内容</div>'
 }) 

var app = new Vue({
  el: '.app',
  data: {}
})

全局注册的组件在任何地方都可以使用,使用组件之前要先注册组件

<div class="app">  
    <my-component></my-component>
 // app 中使用了 my-component
</div>
  
<div class="bpp">
  <my-component></my-component>  
// bpp 中也使用了 my-component
</div>


Vue.component('my-component',{ 
template:'<div>我是组件的内容</div>'
 }) 

var app = new Vue({
  el: '.app',
  data: {}
})

var bpp = new Vue({
  el: '.bpp',
  data: {}
})

组件命名问题

  • 在使用组件的名称时,使用中间划线分词。eg: list-item,驼峰命名是不行的
  • 注册组件的名称可以是驼峰命名或者 使用中间划线分词


局部注册

  • 在 Vue 实例中注册,而不在全局注册。那么同理,局部注册的组件,只能在当前 Vue 实例中使用。
<div class="app">
    <my-component></my-component>
</div>

var app = new Vue({ 
el:'#app', 
components:{
 'my-component':{ 
 template: '我是组件的内容' 
} 
 } 
 })

is属性挂载组件

vue组件的模板在某些情况下会受到html标签的限制,比如 <table> 中只能还有 <tr> , <td> 这些元素,所以直接在table中使用组件是无效的,此时可以使用is属性来挂载组件

 <table>
     <tbody is="my-component"></tbody>
 </table>

相关文章

网友评论

      本文标题:Vue 组件

      本文链接:https://www.haomeiwen.com/subject/nzikkctx.html