查看“Vue从入门到实战:全局组件与局部组件”的源代码
←
Vue从入门到实战:全局组件与局部组件
跳转至:
导航
,
搜索
因为以下原因,您没有权限编辑本页:
您所请求的操作仅限于该用户组的用户使用:
用户
您可以查看与复制此页面的源代码。
==组件的作用== 组件是Vue.js最核心的功能 在前端应用程序中可以采用模块化的开发,实现可重用,可扩展。 组件是带有名字的可复用的Vue实例,能让我们可以用独立可复用的小组件来构建大型应用。 [[文件:vue21021001.png|600px]] ==全局组件与局部组件== 组件可分为全局组件与局部组件 全局注册的组件可以用在其被注册之后的任何 (通过 new Vue) 新创建的 Vue 根实例,也包括其组件树中的所有子组件的模板中。 ===全局组件=== 注册一个全局组件语法格式如下: Vue.component(tagName, options) tagName 为组件名,options 为配置选项。注册后,我们可以使用以下方式来调用组件: <nowiki><tagName></tagName> </nowiki> 代码: <nowiki> <!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></nowiki> 注册全局组件时,Vue.component()方法还可以传入Vue.extend()方法创建的组件构造器。 <nowiki> <!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></nowiki> 注意: 注册组件时,data选项是一个函数(也必须是一个函数),因为组件是可复用的。 组件的内容通过template选项来定义,当使用组件时,组件所在的位置将被template选项内容所代替 组件使用:把组件当成自定义元素,按照元素的方式去使用 组件命名时注意大小写,最好用kebab-case方式去命名,即:button-counter ===局部组件=== <nowiki> <!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></nowiki>
返回至
Vue从入门到实战:全局组件与局部组件
。
导航菜单
个人工具
登录
命名空间
页面
讨论
变种
视图
阅读
查看源代码
查看历史
更多
搜索
导航
首页
最近更改
随机页面
帮助
工具
链入页面
相关更改
特殊页面
页面信息