详解vue.js全局组件和局部组件

这两天学习了Vue.js 感觉组件这个地方知识点挺多的,而且很重要,所以,今天添加一点小笔记。

首先Vue组件的使用有3个步骤,创建组件构造器,注册组件,使用组件3个方面。

代码演示如下:

<!DOCTYPE html> <html> <body> <div> <!-- 3. #app是Vue实例挂载的元素,应该在挂载元素范围内使用组件--> <my-component></my-component> </div> </body> <script src="https://www.jb51.net/js/vue.js"></script> <script> // 1.创建一个组件构造器 var myComponent = Vue.extend({ template: '<div>This is my first component!</div>' }) // 2.注册组件,并指定组件的标签,组件的HTML标签为<my-component> Vue.component('my-component', myComponent) new Vue({ el: '#app' }); </script> </html>

2.理解组件的创建和注册

我们用以下几个步骤来理解组件的创建和注册:

1. Vue.extend()是Vue构造器的扩展,调用Vue.extend()创建的是一个组件构造器,而不是一个具体的组件实例。

2. Vue.extend()构造器有一个选项对象,选项对象的template属性用于定义组件要渲染的HTML。

3. 使用Vue.component()注册组件时,需要提供2个参数,第1个参数时组件的标签,第2个参数是组件构造器。

4. Vue.component()方法内部会调用组件构造器,创建一个组件实例。

5. 组件应该挂载到某个Vue实例下,否则它不会生效。

请注意第5点,以下代码在3个地方使用了<my-component>标签,但只有#app1和#app2下的<my-component>标签才起到作用。

<!DOCTYPE html> <html> <body> <div> <my-component></my-component> </div> <div> <my-component></my-component> </div> <!--该组件不会被渲染--> <my-component></my-component> </body> <script src="https://www.jb51.net/js/vue.js"></script> <script> var myComponent = Vue.extend({ template: '<div>This is a component!</div>' }) Vue.component('my-component', myComponent) var app1 = new Vue({ el: '#app1' }); var app2 = new Vue({ el: '#app2' }) </script> </html>

全局注册和局部注册

调用Vue.component()注册组件时,组件的注册是全局的,这意味着该组件可以在任意Vue示例下使用。

如果不需要全局注册,或者是让组件使用在其它组件内,可以用选项对象的components属性实现局部注册。

上面的示例可以改为局部注册的方式:

<!DOCTYPE html> <html> <body> <div> <!-- 3. my-component只能在#app下使用--> <my-component></my-component> </div> </body> <script src="https://www.jb51.net/js/vue.js"></script> <script> // 1.创建一个组件构造器 var myComponent = Vue.extend({ template: '<div>This is my first component!</div>' }) new Vue({ el: '#app', components: { // 2. 将myComponent组件注册到Vue实例下 'my-component' : myComponent } }); </script> </html>

由于my-component组件是注册在#app元素对应的Vue实例下的,所以它不能在其它Vue实例下使用。

<div> <!-- 不能使用my-component组件,因为my-component是一个局部组件,它属于#app--> <my-component></my-component> </div> <script> new Vue({ el: '#app2' }); </script>

如果你这样做了,浏览器会提示一个错误。

详解vue.js全局组件和局部组件

//注册组件(全局 component) Vue.component("my-component",{ template:'<div>这是一个全局组件测试 </div>' }); new Vue({ el:"#app5" }) //(局部components) new Vue({ el:"#app6", components:{ 'test-component':{ template:"<div>这是一个局部的组件测试</div>" } } });

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwyyjj.html