Vue从入门到实战:全局组件与局部组件
来自CloudWiki
组件的作用
组件是Vue.js最核心的功能
在前端应用程序中可以采用模块化的开发,实现可重用,可扩展。
组件是带有名字的可复用的Vue实例,能让我们可以用独立可复用的小组件来构建大型应用。
全局组件与局部组件
组件可分为全局组件与局部组件
全局注册的组件可以用在其被注册之后的任何 (通过 new Vue) 新创建的 Vue 根实例,也包括其组件树中的所有子组件的模板中。
全局组件
注册一个全局组件语法格式如下:
Vue.component(tagName, options)
tagName 为组件名,options 为配置选项。注册后,我们可以使用以下方式来调用组件:
<tagName></tagName>
代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="vue.js"></script> </head> <body> <div id="app"> <button-counter></button-counter> </div> <script> Vue.component('ButtonCounter', { data: function(){ return { count: 0 } }, template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>' }); new Vue({ el: '#app' }) </script> </body> </html>
注册全局组件时,Vue.component()方法还可以传入Vue.extend()方法创建的组件构造器。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="vue.js"></script> </head> <body> <div id="app"> <button-counter></button-counter> </div> <script> let MyComponent = Vue.extend({ template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>', data: function(){ return { count: 0 } } }); Vue.component('ButtonCounter', MyComponent); new Vue({ el: '#app' }) </script> </body> </html>
注意:
注册组件时,data选项是一个函数(也必须是一个函数),因为组件是可复用的。
组件的内容通过template选项来定义,当使用组件时,组件所在的位置将被template选项内容所代替
组件使用:把组件当成自定义元素,按照元素的方式去使用
组件命名时注意大小写,最好用kebab-case方式去命名,即:button-counter
局部组件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="vue.js"></script> </head> <body> <div id="app"> <button-counter></button-counter> </div> <script> let MyComponent = Vue.extend({ template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>', data: function(){ return { count: 0 } } }); new Vue({ el: '#app', components: { ButtonCounter: MyComponent } /*components: { ButtonCounter : { data: function(){ return { count: 0 } }, template: `<button v-on:click="count++"> You clicked me {{ count }} times. </button>` } }*/ }) </script> </body> </html>