Vue全局组件

Vue全局组件教程

Vue 组件 的出现,就是为了拆分 Vue 实例的代码量的,能够让我们以不同的组件,来划分不同的功能模块,将来我们需要什么样的功能,就可以去调用对应的组件即可。

Vue 组件的模板内容,我们可以使用 template 标签来定义。

Vue全局组件详解

语法

<body> <div id="app"> <componentname></componentname> </div> <!-- 在被控制的 #app 外面,使用 template 元素,定义组件的 HTML 模板结构 --> <template id="tmpname"> </template> </body> <script type="text/javascript"> Vue.component("componentname", { template:"#tmpname" }); var vm = new Vue({ el : '#app' }); </script> </html>

说明

我们首先使用 Vue.component() 方法来创建一个全局的 Vue 组件,该全局组件的名字为 componentname ,全局组件的模板为 tmpname。

接下来,我们在 HTML 元素中使用 template 来定义全局组件的模板。

案例

Vue全局组件案例

<!DOCTYPE html> <html> <head> <title>Vue 全局组件</title> <script type="text/javascript" src="./lib/vue-2.6.10.min.js"></script> </head> <body> <div id="app"> <my-component></my-component> </div> <!-- 在被控制的 #app 外面,使用 template 元素,定义组件的 HTML 模板结构 --> <template id="tmp"> <div> <h1>Vue 全局组件</h1> <h3><a href="http://www.haicoder.net">嗨客网</a></h3> </div> </template> <p>嗨客网(www.haicoder.net)</p> </body> <script type="text/javascript"> Vue.component("my-component", { template:"#tmp" }); var vm = new Vue({ el : '#app' }); </script> </html>

浏览器运行效果,如下图所示:

05 vue component.png

我们首先使用 Vue.component() 方法来创建一个全局的 Vue 组件,该全局组件的名字为 my-component ,全局组件的模板为 tmp。

接下来,我们在 HTML 元素中使用 template 来定义全局组件的模板,并引入我们定义的组件。

Vue全局组件总结

Vue 组件的出现,就是为了拆分 Vue 实例的代码量的,能够让我们以不同的组件,来划分不同的功能模块,将来我们需要什么样的功能,就可以去调用对应的组件即可。