一、Vue组件的使用有3个步骤,创建组件构造器,注册组件,使用组件。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="js/vue.js"></script> </head> <body> <div id="app"> <!-- 3. #app是Vue实例挂载的元素,应该在挂载元素范围内使用组件--> <first-template></first-template> <second-template></second-template> </div> </body> <script> // 1.创建一个组件构造器 var firstTemplate = Vue.extend({ template: '<div>This is my first template!</div>' }); // 2.注册组件,并指定组件的标签,组件的HTML标签为<my-template> Vue.component('first-template', firstTemplate); // 合并第一步和第二步 Vue.component('second-template',{ template:'<div>This is my second template!</div>' }); new Vue({ el: '#app' }); </script> </html>
二、理解组件的创建和注册
1. Vue.extend()
是Vue构造器的扩展,调用Vue.extend()
创建的是一个组件构造器,而不是一个具体的组件实例。
2. Vue.extend()
构造器有一个选项对象,选项对象的template
属性用于定义组件要渲染的HTML。
3. 使用Vue.component()
注册组件时,需要提供2个参数,第1个参数时组件的标签,第2个参数是组件构造器。
4. Vue.component()
方法内部会调用组件构造器,创建一个组件实例。
5. 组件应该挂载到某个Vue实例下,否则它不会生效。
三、全局注册和局部注册
调用Vue.component()
注册组件时,组件的注册是全局的,这意味着该组件可以在任意Vue示例下使用。
如果不需要全局注册,或者是让组件使用在其它组件内,可以用选项对象的components属性实现局部注册。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <script src="js/vue.js"></script> </head> <body> <div id="demo"> <!-- 全局注册--> <demo-template></demo-template> <!-- 局部注册--> <demo-child></demo-child> </div> </body> <script> //全局注册 Vue.component('demo-template',{ template:'<div>这是一个全局组件!</div>' }); new Vue({ el:"#demo" }); //局部注册 new Vue({ el:"#demo", components:{ 'demo-child':{ template:'<p>这是一个局部组件!</p>' } } }); </script> </html>