Vue 组件化的思想大大提高了模块的复用性和开发的效率,在使用组件时,一般分为几个步骤,分别是:定义组件、引入组件,注册组件,使用组件。本节主要针对Vue中如何注册组件进行阐述。
下面我们一起来看如何全局注册组件,如何局部注册组件。

页面显示结果如下:

【说明】:
1. com-one com-two 为全局注册组件, com-three com-four 为局部注册组件;
2. 全局注册组件为 Vue.component()方法;局部注册组件为 components 属性,它的属性值是一个对象;
3. 在用脚手架时,我们更多用到的是在单文件组件中局部注册组件。
[代码]:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>test1</title>
</head>
<body>
<div id="app">
<com-one></com-one> <com-two></com-two>
<com-three></com-three> <com-four></com-four>
</div>
</body>
<!-- 定义组件 -->
<template id="comTwo">
<div>
<h1>this is com-two</h1>
</div>
</template>
<template id="comFour">
<div>
<h2>this is com-four</h2>
</div>
</template>
<script src="./vue.js"></script>
<script>
// 全局注册1: 第二个参数中template的属性值为子组件的具体内容(注册时定义组件)
Vue.component('com-one',{
template: `<h1>this is com-one</h1>`
})
// 全局注册2: 第二个参数中template的属性值为<template>模板的'#id'
// (将子组件的具体内容单独写入<template>中,放到<body>元素之后,<script>元素之前)
Vue.component('com-two',{
template: '#comTwo',
})
let vm = new Vue({
el: '#app',
data: {},
// 局部注册:(类似于全局注册)
components: {
"com-three": {
template: `<h2>this is com-three</h2>`
},
"com-four": {
template: '#comFour'
}
}
})
</script>
</html>
