工程化开发
开发 Vue 的两种方式:
-
核心包传统开发模式:基于 html / css / js 文件,直接引入核心包,开发 Vue
-
工程化开发模式:基于构建工具( 例如 webpack )的环境中开发 Vue
问题:
- webpack 配置麻烦
- 雷同的基础配置
- 缺乏统一标准
需要一个工具,生成标准化的配置,即 Vue 脚手架
脚手架
基本使用
Vue CLI
是 Vue 官方提供的一个全局命令工具,可以帮助我们快速创建一个开发 Vue 项目的标准化基础架子(集成了 webpack 配置)- 好处:
- 开箱即用,零配置
- 内置 babel 等工具
- 标准化
- 使用步骤:
- 全局安装 (一次) :
yarn global add @vue/cli
或npm i @vue/cli -g
- 查看 Vue 版本:
vue --version
- 创建项目架子:
vue create project-name
( 项目名不能用中文 ) - 启动项目:
yarn serve 或 npm run serve
( 找 package.json )
- 全局安装 (一次) :
目录文件介绍
运行流程
组件化开发
概念
- 组件化:一个页面可以拆分成一个个组件,每个组件有着自己独立的结构、样式、行为,便于维护,利于复用
- 根组件:整个应用最上层的组件,包裹所有普通小组件
App.vue( 根组件 )的三个组成部分:
![在这里插入图片描述](https://img-blog.csdnimg.cn/307b4244992a4829b9a0efda237bfdcc.png)
注册普通组件
普通组件注册的两种方式:
-
局部注册
-
全局注册
局部注册
步骤:
- 创建 .vue 文件(三个组成部分)
- 在使用的组件内先导入再注册(
components
),最后使用
示例代码如下(App.vue):
<template>
<div class="App">
<!--头部组件-->
<AHeaderName></AHeaderName>
<!--主体组件-->
<AMain></AMain>
<!--底部组件-->
<AFooter></AFooter>
</div>
</template>
<script>
// 导入组件对象(对象名可以自定义)
import AHeader from './components/AHeader.vue'
import AMain from './components/AMain.vue'
import AFooter from './components/AFooter.vue'
export default {
components: {
// 组件名: 组件对象(组件名也可以自定义)
AHeaderName: AHeader,
AMain: AMain,
// 简写
AFooter
}
}
</script>
<style>
.App {
width: 600px;
height: 700px;
background-color: skyblue;
margin: 0 auto;
padding: 20px;
}
</style>
AHeader:
<template>
<div class="header">
我是校花
</div>
</template>
<script>
</script>
<style>
.header {
height: 100px;
line-height: 100px;
text-align: center;
font-size: 30px;
background-color: #8064a2;
color: white;
}
</style>
AMain:
<template>
<div class="main">
我是校花-main
</div>
</template>
<script>
</script>
<style>
.main {
height: 400px;
line-height: 400px;
text-align: center;
font-size: 30px;
background-color: #f79646;
color: white;
margin: 20px 0;
}
</style>
AFooter 组件:
<template>
<div class="footer">
我是校花-footer
</div>
</template>
<script>
</script>
<style>
.footer {
height: 100px;
line-height: 100px;
text-align: center;
font-size: 30px;
background-color: #4f81bd;
color: white;
}
</style>
全局注册
- 全局注册:所有组件内都能使用(无需导入注册)
- 步骤
- 创建 .vue 文件(三个组成部分)
- main.js 中进行全局注册
示例代码如下( main.js ):
import Vue from 'vue'
import App from './App.vue'
import AButton from './components/AButton.vue'
Vue.config.productionTip = false
// 全局注册
Vue.component('AButton', AButton)
new Vue({
// el: '#app',
// render: h => h(App),
render: (createElement) => {
// 基于 App 创建元素结构
return createElement(App)
}
}).$mount('#app')
// .$mount('#app') 和 el: '#app' 作用一样