Vue 组件

2019-07-10  本文已影响0人  lyp82nkl

对组件的理解 :

组件 (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: {}
})

组件命名问题

局部注册

<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>
上一篇下一篇

猜你喜欢

热点阅读