Vue.js 全面技术指南

目录

1. Vue.js 基础入门

1.1 脚手架安装

1.2 基础指令使用

v-bind 动态绑定

v-model 双向绑定

1.3 条件渲染

2. 核心概念详解

2.1 计算属性与监听器

2.2 Methods 方法

2.3 Filters 过滤器

3. 组件化开发

3.1 组件基础

3.2 组件通信

4. 实战应用

4.1 Element UI 使用

4.2 Axios 网络请求

4.3 路由配置

5. 进阶技巧

5.1 BOM 定时器

5.2 DOM 操作

总结

Vue.js 高级开发指南 2.0

1. 高级特性深度解析

1.1 自定义指令

1.2 混入 (Mixins)

2. 性能优化技巧

2.1 动态组件与异步组件

2.2 虚拟列表实现

3. 状态管理进阶

3.1 Vuex 模块化

3.2 数据持久化

4. 高级组件模式

4.1 函数式组件

4.2 高阶组件 (HOC)

5. 测试与调试

5.1 单元测试

5.2 性能监控

6. 工程化实践

6.1 自动化部署

6.2 代码规范

7. 安全性考虑

7.1 XSS 防护

7.2 路由安全

总结与最佳实践


1. Vue.js 基础入门

1.1 脚手架安装

首先我们需要安装 Vue CLI:

# 安装 Vue CLI
npm install -g @vue/cli
​
# 创建新项目
vue create my-project

1.2 基础指令使用

v-bind 动态绑定
v-model 双向绑定

1.3 条件渲染

2. 核心概念详解

2.1 计算属性与监听器

2.2 Methods 方法

2.3 Filters 过滤器

3. 组件化开发

3.1 组件基础



3.2 组件通信









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 操作

总结

本文涵盖了 Vue.js 的主要知识点,包括:

  • 基础指令(v-bind、v-model、v-for 等)

  • 组件化开发

  • 生命周期

  • 路由配置

  • 状态管理

  • 网络请求

  • UI 框架集成

建议读者在实践中多加运用这些概念,真正掌握 Vue.js 的精髓。

注意事项:

  1. 合理使用计算属性和监听器

  2. 注意组件之间的数据流向

  3. 及时清理定时器等资源

  4. 遵循 Vue.js 的设计理念和最佳实践

Vue.js 高级开发指南 2.0

1. 高级特性深度解析

1.1 自定义指令

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 动态组件与异步组件

2.2 虚拟列表实现

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 函数式组件

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()
  }
})

总结与最佳实践

  1. 性能优化核心要点

    • 合理使用异步组件

    • 实现虚拟列表

    • 避免不必要的组件重渲染

    • 使用函数式组件处理简单逻辑

  2. 工程化建议

    • 统一的代码规范

    • 自动化测试

    • CI/CD 流程

    • 模块化和组件化

  3. 安全性建议

    • 输入数据验证

    • XSS 防护

    • CSRF 防护

    • 敏感信息加密

  4. 开发效率提升

    • 使用 TypeScript

    • 合理的目录结构

    • 组件文档化

    • Git 工作流规范

这些进阶知识点将帮助你构建更健壮、可维护的 Vue.js 应用。建议根据项目需求逐步实践这些概念。

你可能感兴趣的:(vue.js,前端,javascript)