1. Vue.js 基础入门
1.1 脚手架安装
首先我们需要安装 Vue CLI:
# 安装 Vue CLI npm install -g @vue/cli # 创建新项目 vue create my-project
1.2 基础指令使用
v-bind 动态绑定
<template>
<div>
<img v-bind:src="imageUrl" />
<!-- 简写形式 -->
<div :class="className"></div>
</div>
</template>
<script>
export default {
data() {
return {
imageUrl: 'https://example.com/image.jpg',
className: 'active'
}
}
}
</script>
v-model 双向绑定
<template>
<div>
<input v-model="message" />
<p>输入的内容:{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: ''
}
}
}
</script>
1.3 条件渲染
<template> <div> <h1 v-if="type === 'A'">A类型</h1> <h1 v-else-if="type === 'B'">B类型</h1> <h1 v-else>其他类型</h1> <!-- v-show --> <p v-show="isShow">使用 display 控制显示隐藏</p> </div> </template>
2. 核心概念详解
2.1 计算属性与监听器
<template>
<div>
<p>计算属性:{{ fullName }}</p>
</div>
</template>
<script>
export default {
data() {
return {
firstName: '张',
lastName: '三'
}
},
computed: {
fullName() {
return this.firstName + this.lastName
}
},
watch: {
firstName(newVal, oldVal) {
console.log('firstName 发生变化:', newVal, oldVal)
}
}
}
</script>
2.2 Methods 方法
<template>
<div>
<button @click="handleClick">点击事件</button>
<!-- 事件修饰符 -->
<button @click.stop="handleClick">阻止冒泡</button>
<button @click.prevent="handleClick">阻止默认行为</button>
</div>
</template>
<script>
export default {
methods: {
handleClick(event) {
console.log('按钮被点击')
}
}
}
</script>
2.3 Filters 过滤器
<template>
<div>
{{ price | formatPrice }}
</div>
</template>
<script>
export default {
data() {
return {
price: 100
}
},
filters: {
formatPrice(value) {
return '¥' + value.toFixed(2)
}
}
}
</script>
3. 组件化开发
3.1 组件基础
<!-- 子组件:ChildComponent.vue --> <template> <div> <slot></slot> </div> </template> <!-- 父组件 --> <template> <div> <child-component> <p>这是插槽内容</p> </child-component> </div> </template>
3.2 组件通信
<!-- 父组件 -->
<template>
<div>
<child-component
:message="parentMessage"
@child-event="handleChildEvent"
/>
</div>
</template>
<script>
export default {
data() {
return {
parentMessage: '父组件的数据'
}
},
methods: {
handleChildEvent(data) {
console.log('接收到子组件数据:', data)
}
}
}
</script>
<!-- 子组件 -->
<template>
<div>
<p>{{ message }}</p>
<button @click="sendToParent">向父组件发送数据</button>
</div>
</template>
<script>
export default {
props: ['message'],
methods: {
sendToParent() {
this.$emit('child-event', '子组件的数据')
}
}
}
</script>
4. 实战应用
4.1 Element UI 使用
// main.js import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI)
4.2 Axios 网络请求
import axios from 'axios'
// GET 请求
axios.get('/api/data')
.then(response => {
console.log(response.data)
})
.catch(error => {
console.error(error)
})
// POST 请求
axios.post('/api/submit', {
name: '张三',
age: 25
})
4.3 路由配置
// router/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: () => import('../views/Home.vue')
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
}
]
export default new VueRouter({
routes
})
5. 进阶技巧
5.1 BOM 定时器
export default {
data() {
return {
timer: null
}
},
mounted() {
this.timer = setInterval(() => {
console.log('定时器执行')
}, 1000)
},
beforeDestroy() {
// 清除定时器
clearInterval(this.timer)
}
}
5.2 DOM 操作
<template>
<div>
<div ref="myDiv">DOM 元素</div>
</div>
</template>
<script>
export default {
mounted() {
// 访问 DOM 元素
console.log(this.$refs.myDiv)
}
}
</script>
总结
本文涵盖了 Vue.js 的主要知识点,包括:
-
基础指令(v-bind、v-model、v-for 等)
-
组件化开发
-
生命周期
-
路由配置
-
状态管理
-
网络请求
-
UI 框架集成
建议读者在实践中多加运用这些概念,真正掌握 Vue.js 的精髓。
注意事项:
-
合理使用计算属性和监听器
-
注意组件之间的数据流向
-
及时清理定时器等资源
-
遵循 Vue.js 的设计理念和最佳实践
Vue.js 高级开发指南 2.0
1. 高级特性深度解析
1.1 自定义指令
<template>
<div>
<!-- 使用自定义指令 -->
<input v-focus v-model="message">
<div v-loading="isLoading">加载中...</div>
</div>
</template>
<script>
export default {
directives: {
// 自动聚焦指令
focus: {
inserted(el) {
el.focus()
}
},
// 加载指令
loading: {
update(el, binding) {
if (binding.value) {
el.classList.add('loading')
} else {
el.classList.remove('loading')
}
}
}
}
}
</script>
1.2 混入 (Mixins)
// mixins/common.js
export const commonMixin = {
data() {
return {
sharedData: 'mixin数据'
}
},
methods: {
sharedMethod() {
console.log('mixin方法')
}
},
created() {
console.log('mixin created钩子')
}
}
// 使用混入
import { commonMixin } from './mixins/common'
export default {
mixins: [commonMixin],
created() {
console.log(this.sharedData) // 可访问mixin中的数据
}
}
2. 性能优化技巧
2.1 动态组件与异步组件
<template>
<div>
<!-- 动态组件 -->
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
<!-- 异步组件 -->
<async-component v-if="showAsync"></async-component>
</div>
</template>
<script>
export default {
components: {
AsyncComponent: () => ({
component: import('./AsyncComponent.vue'),
loading: LoadingComponent,
error: ErrorComponent,
delay: 200,
timeout: 3000
})
}
}
</script>
2.2 虚拟列表实现
<template>
<div class="virtual-list" @scroll="handleScroll">
<div class="virtual-list-phantom" :style="{ height: listHeight + 'px' }">
<div class="virtual-list-content" :style="{ transform: getTransform }">
<div class="virtual-list-item"
v-for="item in visibleData"
:key="item.id">
{{ item.content }}
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
listData: [], // 原始数据
itemHeight: 50, // 每项高度
visibleCount: 10, // 可视区域显示的数量
startIndex: 0, // 起始索引
endIndex: 0 // 结束索引
}
},
computed: {
listHeight() {
return this.listData.length * this.itemHeight
},
visibleData() {
return this.listData.slice(this.startIndex, this.endIndex)
},
getTransform() {
return `translate3d(0, ${this.startIndex * this.itemHeight}px, 0)`
}
},
methods: {
handleScroll(e) {
const scrollTop = e.target.scrollTop
this.startIndex = Math.floor(scrollTop / this.itemHeight)
this.endIndex = this.startIndex + this.visibleCount
}
}
}
</script>
3. 状态管理进阶
3.1 Vuex 模块化
// store/modules/user.js
const state = {
userInfo: null,
token: null
}
const mutations = {
SET_USER_INFO(state, userInfo) {
state.userInfo = userInfo
}
}
const actions = {
async login({ commit }, credentials) {
try {
const response = await api.login(credentials)
commit('SET_USER_INFO', response.data)
} catch (error) {
throw new Error(error)
}
}
}
export default {
namespaced: true,
state,
mutations,
actions
}
// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
user
}
})
3.2 数据持久化
// store/plugins/persistedState.js
import createPersistedState from 'vuex-persistedstate'
export default createPersistedState({
key: 'vuex',
storage: window.localStorage,
paths: ['user.token'] // 只持久化特定数据
})
// store/index.js
import persistedState from './plugins/persistedState'
export default new Vuex.Store({
plugins: [persistedState]
})
4. 高级组件模式
4.1 函数式组件
<template functional>
<div class="functional-component">
{{ props.message }}
<slot></slot>
</div>
</template>
<script>
export default {
props: {
message: String
}
}
</script>
4.2 高阶组件 (HOC)
// HOC/withLog.js
export default function withLog(WrappedComponent) {
return {
mounted() {
console.log(`组件 ${WrappedComponent.name} 已挂载`)
},
props: WrappedComponent.props,
render(h) {
return h(WrappedComponent, {
props: this.$props,
on: this.$listeners
})
}
}
}
// 使用 HOC
import withLog from './HOC/withLog'
import BaseComponent from './BaseComponent.vue'
export default withLog(BaseComponent)
5. 测试与调试
5.1 单元测试
// tests/unit/HelloWorld.spec.js
import { shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'
describe('HelloWorld.vue', () => {
it('renders props.msg when passed', () => {
const msg = 'new message'
const wrapper = shallowMount(HelloWorld, {
propsData: { msg }
})
expect(wrapper.text()).toMatch(msg)
})
})
5.2 性能监控
Vue.config.performance = true
// 监听组件性能
Vue.component('monitored-component', {
created() {
console.time('组件渲染时间')
},
mounted() {
console.timeEnd('组件渲染时间')
},
beforeUpdate() {
console.time('组件更新时间')
},
updated() {
console.timeEnd('组件更新时间')
}
})
6. 工程化实践
6.1 自动化部署
# .gitlab-ci.yml
stages:
- install
- build
- deploy
install:
stage: install
script:
- npm install
build:
stage: build
script:
- npm run build
deploy:
stage: deploy
script:
- rsync -av dist/ user@server:/path/to/deploy
6.2 代码规范
// .eslintrc.js
module.exports = {
root: true,
env: {
node: true
},
extends: [
'plugin:vue/essential',
'@vue/standard'
],
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
}
}
7. 安全性考虑
7.1 XSS 防护
// 使用 v-html 时的安全处理
import sanitizeHtml from 'sanitize-html'
export default {
computed: {
safeHtml() {
return sanitizeHtml(this.rawHtml, {
allowedTags: ['b', 'i', 'em', 'strong', 'a'],
allowedAttributes: {
'a': ['href']
}
})
}
}
}
7.2 路由安全
// router/index.js
router.beforeEach((to, from, next) => {
const token = store.state.user.token
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!token) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next()
}
})
总结与最佳实践
-
性能优化核心要点:
-
合理使用异步组件
-
实现虚拟列表
-
避免不必要的组件重渲染
-
使用函数式组件处理简单逻辑
-
-
工程化建议:
-
统一的代码规范
-
自动化测试
-
CI/CD 流程
-
模块化和组件化
-
-
安全性建议:
-
输入数据验证
-
XSS 防护
-
CSRF 防护
-
敏感信息加密
-
-
开发效率提升:
-
使用 TypeScript
-
合理的目录结构
-
组件文档化
-
Git 工作流规范
-
这些进阶知识点将帮助你构建更健壮、可维护的 Vue.js 应用。建议根据项目需求逐步实践这些概念。
301

被折叠的 条评论
为什么被折叠?



