Vue 组件 的出现,就是为了拆分 Vue 实例的代码量的,能够让我们以不同的组件,来划分不同的功能模块,将来我们需要什么样的功能,就可以去调用对应的组件即可。
Vue 全局组件可以直接使用 Vue.component 来定义。使用 Vue.component 定义的全局组件,template 模板内容有且只能有一个根 HTML 元素,否则无法正常展示。
<body>
<div id="app">
<my-component></my-component>
</div>
</body>
<script type="text/javascript">
Vue.component("my-component", {
template:"<h1>我是全局组件</h1>"
});
var vm = new Vue({
el : '#app1'
});
</script>
首先使用 Vue.component 来定义一个 Vue 的全局组件,组件名叫 my-component,组件的模板内容为 template 所定义的内容。使用 html 标签引入的方式,引入我们刚定义的组件。
<!DOCTYPE html>
<html>
<head>
<title>Vue 全局组件</title>
<script type="text/javascript" src="./lib/vue-2.6.10.min.js"></script>
</head>
<body>
<div id="app1">
<my-component></my-component>
</div>
<div id="app2">
<my-component></my-component>
</div>
<p>嗨客网(www.haicoder.net)</p>
</body>
<script type="text/javascript">
Vue.component("my-component", {
template:"<h1>我是全局组件</h1>"
});
var vm = new Vue({
el : '#app1'
});
var vm = new Vue({
el : '#app2'
});
</script>
</html>
浏览器运行效果,如下图所示:
使用 Vue.component 定义了一个名为 my-component 的全局组件,组件的模板内容为一个 h1 标签。
因为定义的是全局组件,所以接下来我们在两个 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="app1">
<my-component></my-component>
<p>嗨客网(www.haicoder.net)</p>
</div>
</body>
<script type="text/javascript">
Vue.component("my-component", {
template:"<h1>我是全局组件</h1><span>你看不到我</span>"
});
var vm = new Vue({
el : '#app1'
});
</script>
</html>
浏览器运行效果,如下图所示:
这里定义的全局组件的模板根元素有两个,一个是 h1 ,一个是 span,但结果我们发现,页面只展示了 h1 标签,并未展示出 span 标签的内容,因为模板根元素只支持一个。
Vue 组件的出现,就是为了拆分 Vue 实例的代码量的,能够让我们以不同的组件,来划分不同的功能模块,将来我们需要什么样的功能,就可以去调用对应的组件即可。
使用 Vue.component 定义的全局组件,template 模板内容有且只能有一个根 HTML 元素,否则无法正常展示。