一、Vue与VueComponent原型关系解析
1. 原型链关系图解
在Vue中,组件实例(VueComponent)与Vue实例之间存在特殊的原型链关系:
VueComponent.prototype.__proto__ === Vue.prototype
这种设计使得所有组件都能访问Vue原型上定义的方法和属性。
2. 原理验证示例
javascript
// 在Vue原型上添加方法
Vue.prototype.$sayHello = function() {
console.log('Hello from Vue prototype!')
}
// 创建组件
const Company = Vue.extend({
created() {
this.$sayHello() // 可以调用Vue原型上的方法
}
})
// 使用组件
new Vue({
el: '#app',
components: { Company },
template: '<Company/>'
})
关键点:
-
组件实例可以访问Vue原型上的属性和方法
-
这种设计实现了Vue功能的扩展性
-
这也是为什么能在组件中使用
this.$router
、this.$store
等全局属性的原因
二、单文件组件
1. 文件结构与命名规范
推荐的单文件组件结构:
javascript
MyComponent.vue
├── <template> // 组件模板
├── <script> // 组件逻辑
└── <style> // 组件样式
命名建议:
-
文件名使用PascalCase(首字母大写)
-
与组件名保持一致
-
多单词命名使用大驼峰
-
避免与HTML元素冲突
2. 组件导出方式对比
2.1 分别暴露
javascript
<script>
export const Company = {
data() {
return { name: "Vue Inc." }
}
}
</script>
使用方式:
html
import { Company } from './Company.vue'
2.2 统一暴露
html
<script>
const Company = {
data() {
return { name: "Vue Inc." }
}
}
export { Company }
</script>
2.3 默认暴露(推荐)
html
<script>
export default {
name: 'Company',
data() {
return { name: "Vue Inc." }
}
}
</script>
使用方式:
html
import Company from './Company.vue'
最佳实践:
-
优先使用默认暴露
-
始终指定
name
选项 -
保持组件名称与文件名一致
三、Vue脚手架工程化
1.1 配置国内镜像
html
// 淘宝镜像
npm config set registry https://registry.npm.taobao.org
// 阿里镜像
npm config set registry https://registry.npmmirror.com/
1.2 安装Vue CLI
html
npm install -g @vue/cli
1.3 创建项目
html
vue create my-project
cd my-project
npm run serve
2. 项目结构
html
my-project
├── public/ # 静态资源
│ ├── index.html # 主入口HTML
│ └── favicon.ico # 网站图标
├── src/
│ ├── assets/ # 静态资源
│ ├── components/ # 组件目录
│ ├── App.vue # 根组件
│ └── main.js # 应用入口
├── .gitignore # Git忽略配置
├── babel.config.js # Babel配置
└── package.json # 项目配置
3. 核心文件解析
3.1 public/index.html
html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<!-- 针对IE浏览器的一个特殊配置,让IE浏览器以最高的渲染级别渲染页面 >=IE8 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- 开启移动端的理想视口 -->
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<!-- 配置页签图表,BASE_URL指的public路径 -->
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<!-- 配置网页标题 从package.json中获取标题-->
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<!-- 当浏览器不支持js,以下代码会出现在页面上 -->
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<!-- 容器 -->
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
3.2 src/main.js
html
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App)
}).$mount('#app')
3.3 src/App.vue
html
<template>
<div id="app">
<Company/>
</div>
</template>
<script>
import Company from './components/Company.vue'
export default {
name: 'App',
components: { Company }
}
</script>
<style>
/* 全局样式 */
</style>
四、Vue完整版与运行时版本区别
1. 核心差异对比
特性 | vue.js (完整版) | vue.runtime.js (运行时版) |
---|---|---|
模板解析器 | 包含 | 不包含 |
体积 | 较大 | 较小(约轻30%) |
使用方式 | 支持template选项 | 必须使用render函数 |
适用场景 | 直接HTML引用 | 构建工具配合使用 |
2. 使用示例对比
完整版使用方式
html
new Vue({
el: '#app',
template: '<div>{{ message }}</div>',
data: {
message: 'Hello Vue!'
}
})
运行时版使用方式
html
new Vue({
el: '#app',
render(h) {
return h('div', this.message)
},
data: {
message: 'Hello Vue!'
}
})
3. 脚手架中的配置
在vue.config.js中可以配置使用的版本:
html
module.exports = {
configureWebpack: {
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js' // 使用完整版
}
}
}
}
五、高级配置与优化建议
1. 自定义脚手架配置
创建vue.config.js进行个性化配置:
html
module.exports = {
// 基本路径
publicPath: process.env.NODE_ENV === 'production' ? '/production-sub-path/' : '/',
// 输出目录
outputDir: 'dist',
// 静态资源目录
assetsDir: 'static',
// 是否启用eslint
lintOnSave: process.env.NODE_ENV !== 'production',
// 生产环境sourceMap
productionSourceMap: false,
// 开发服务器配置
devServer: {
port: 8080,
proxy: {
'/api': {
target: 'http://localhost:3000',
changeOrigin: true
}
}
}
}
2. 性能优化建议
- 代码分割:
html
const Company = () => import('./components/Company.vue')
- 第三方库CDN引入:
html
module.exports = {
configureWebpack: {
externals: {
vue: 'Vue',
'vue-router': 'VueRouter'
}
}
}
Gzip压缩:
html
npm install compression-webpack-plugin --save-dev
图片优化:
html
module.exports = {
chainWebpack: config => {
config.module
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({ bypassOnDebug: true })
}
}
六、总结与最佳实践
1. 组件开发黄金法则
-
单一职责原则:每个组件只做一件事
-
明确接口:通过props和events定义清晰的组件API
-
可复用设计:考虑组件的通用性
-
命名一致性:保持文件名、组件名和注册名一致
2. 工程化实践建议
- 项目结构:
html
src/
├── components/ # 基础组件
├── views/ # 路由组件
├── store/ # Vuex相关
├── router/ # 路由配置
├── api/ # 接口封装
└── utils/ # 工具函数
-
代码规范:
-
使用ESLint + Prettier统一代码风格
-
添加JSDoc注释
-
编写组件文档(可使用Storybook)
-
-
测试策略:
-
单元测试:Jest + Vue Test Utils
-
E2E测试:Cypress
-
学习路径推荐
通过本文的系统学习,您已经掌握了Vue单文件组件和脚手架工程化开发的核心知识。接下来可以通过实际项目实践来巩固这些概念,逐步提升Vue开发技能水平。
-
掌握单文件组件开发
-
熟悉Vue CLI工程化配置
-
学习Vue Router和Vuex
-
了解服务端渲染(Nuxt.js)
-
探索Vue 3新特性