0.全局组件的弊端
对于全局组件<zujian></zujian>
,
Vue.component('zujian', {
template: `<ul>
<li>1111</li>
<li>2222</li>
<li>3333</li>
</ul>`
});
有如下缺点:
- 全局定义:强制要求每个 component 中的命名不得重复
- 字符串模板:缺乏语法高亮,在 HTML 有多行的时候,需要用到丑陋的 \
- **不支持 CSS:**意味着当 HTML 和 JavaScript 组件化时,CSS 明显被遗漏
- 没有构建步骤:限制只能使用 HTML 和 ES5 JavaScript,而不能使用预处理器
解决方法:单文件组件
1.单文件组件的后缀名和组成
后缀:.vue
组成
-. 模板页面
<template>
//页面模板
</template>
- JS 模块对象
<script>
export default {
data() {return {}},
methods: {},
computed: {},
components: {}
}
</script>
- 样式
<style>
//样式定义
</style>
3.单文件组件的使用
步骤
1. 引入组件
2. 映射成标签
3. 使用组件标签
示例:在vue-cli项目中多个单文件组件引入到App.Vue中
App.vue
<template>
<div id="app">
<!-- 3.组件调用 -->
<Navbar></Navbar>
<Sidebar></Sidebar>
</div>
</template>
<script>
import Vue from "vue"
// 1.组件引入
import Navbar from "./components/Navbar"
import Sidebar from "./components/Sidebar"
// 2.全局组件注册
Vue.component("Navbar",Navbar);//前面的"Navbar"是组件名,后面的Navbar是引入的外部组件注册
Vue.component("Sidebar",Sidebar);
export default {
};
</script>
<style>
</style>
Navbar.vue
<template>
<div>
我是navbar
</div>
</template>
Sidebar.vue
<template>
<div>
我是sidebar
</div>
</template>