基本概念
组件允许我们将 UI 划分为独立的、可重用的部分,并且可以对每个部分进行单独的思考。在实际应用中,组件常常被组织成层层嵌套的树状结构,和嵌套 HTML 元素的方式类似:
![](https://img-blog.csdnimg.cn/img_convert/90abdb1e78502ba78e0063f129ede666.png)
[图1] 组件分布结构
注意: 本文内容均为 选项式!
基本使用
定义组件
使用构建步骤: 将 Vue 组件定义在一个单独的 .vue 文件中,即单文件组件(SFC)。
Child.vue:
<script>
export default {
data() {
return {
msg: 'this is a message.'
}
},
}
</script>
<template>
<h2>{
{ msg }}</h2>
</template>
不使用构建步骤: 组件以一个包含 Vue 特定选项的 .js 文件来定义。
Child.js:
export default {
data() {
return {
msg: 'this is a message.'
}
},
template: `
<h2>{
{ msg }}</h2>
`
}
使用组件
1. SFC 实现模板
<template>部分:
<template>
<Child />
</template>
JS部分:
<script>
// 引入组件
import Child from './Child.vue'
export default {
// 在 components 选项上注册组件
components: {
Child,
},
}
}
</script>
2. JS 中实现脚本
使用JS编写脚本,也可以实现类似SFC的效果。
DOM部分:
<div id="app">
<Child></Child>
</div>
JS部分: