Vue 2看这篇就够了

2024-06-10 14:12
文章标签 javascript vue frontend 这篇

本文主要是介绍Vue 2看这篇就够了,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Vue 2 技术文档

Vue.js 是一款用于构建用户界面的渐进式框架。与其他重量级框架不同的是,Vue 被设计为可以自底向上逐层应用。Vue 的核心库只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合。而 Vue.js 2(以下简称 Vue 2)则是该框架的一个重要版本,提供了许多新的特性和改进。本文将详细介绍 Vue 2 的各项功能及其使用方法。

目录

  • Vue 2 技术文档
    • 1. Vue 2 的安装和基本使用
      • 安装 Vue 2
      • 创建 Vue 实例
    • 2. 模板语法
      • 插值
      • 指令
      • 计算属性
    • 3. Vue 实例
      • 实例属性与方法
      • 生命周期钩子
    • 4. 组件
      • 定义与注册组件
      • 组件通信
        • 父子组件通信
    • 5. 路由
      • 安装 Vue Router
      • 配置路由
      • 动态路由匹配
    • 6. 状态管理
      • 安装 Vuex
      • Vuex 基本使用
      • 模块化
    • 7. 过渡与动画
      • 过渡类名
      • 动画
    • 8. HTTP 请求
      • 使用 axios
      • 在 Vue 组件中使用 HTTP 请求
    • 9. 表单处理
      • 基本表单处理
      • 表单修饰符
    • 10. 插件
      • 使用插件
      • 创建插件
    • 11. 实践
      • 代码结构
      • 性能优化

1. Vue 2 的安装和基本使用

安装 Vue 2

Vue 2 提供了多种安装方式:

  1. 通过 CDN 引入:

    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    
  2. 使用 npm 安装:

    npm install vue@2
    
  3. 使用 Vue CLI 创建项目:

    npm install -g @vue/cli
    vue create my-project
    cd my-project
    npm run serve
    

创建 Vue 实例

一个简单的 Vue 实例示例:

<!DOCTYPE html>
<html>
<head><title>Vue 2 示例</title><script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
</head>
<body><div id="app">{{ message }}</div><script>new Vue({el: '#app',data: {message: 'Hello, Vue 2!'}});</script>
</body>
</html>

在这个示例中,我们创建了一个新的 Vue 实例,并将其挂载到 #app 元素上。data 对象中的 message 属性将显示在页面上。

2. 模板语法

插值

Vue 允许在模板中使用双花括号语法进行数据绑定:

<div id="app">{{ message }}
</div>

也可以在属性中使用:

<div id="app"><span v-bind:title="message">鼠标悬停几秒钟查看此处动态绑定的提示信息!</span>
</div>

指令

指令(Directives)是带有 v- 前缀的特殊属性:

  • v-bind: 绑定属性
  • v-if: 条件渲染
  • v-for: 列表渲染
  • v-on: 事件监听

示例:

<div id="app"><p v-if="seen">现在你看到我了</p>
</div><script>new Vue({el: '#app',data: {seen: true}});
</script>

计算属性

计算属性是基于依赖进行缓存的属性:

<div id="app">{{ reversedMessage }}
</div><script>new Vue({el: '#app',data: {message: 'Hello'},computed: {reversedMessage: function() {return this.message.split('').reverse().join('')}}});
</script>

在这个示例中,reversedMessage 是一个计算属性,它基于 message 计算出一个反转字符串。

3. Vue 实例

实例属性与方法

Vue 实例有许多属性和方法,如 eldatamethods 等:

<div id="app"><p>{{ message }}</p><button @click="reverseMessage">Reverse Message</button>
</div><script>new Vue({el: '#app',data: {message: 'Hello Vue!'},methods: {reverseMessage: function () {this.message = this.message.split('').reverse().join('')}}});
</script>

生命周期钩子

Vue 实例在生命周期内会触发一些钩子函数:

<script>new Vue({el: '#app',data: {message: 'Hello Vue!'},created: function () {console.log('实例已创建');},mounted: function () {console.log('实例已挂载');},updated: function () {console.log('实例已更新');},destroyed: function () {console.log('实例已销毁');}});
</script>

4. 组件

定义与注册组件

Vue 组件是可复用的 Vue 实例,通常我们可以通过 Vue.component 方法来全局注册一个组件:

<div id="app"><my-component></my-component>
</div><script>Vue.component('my-component', {template: '<div>A custom component!</div>'});new Vue({el: '#app'});
</script>

也可以通过 components 选项局部注册组件:

<div id="app"><my-component></my-component>
</div><script>var myComponent = {template: '<div>A custom component!</div>'};new Vue({el: '#app',components: {'my-component': myComponent}});
</script>

组件通信

父子组件通信

在这里插入图片描述

父组件通过 props 向子组件传递数据:

<div id="app"><child message="Hello from parent"></child>
</div><script>Vue.component('child', {props: ['message'],template: '<div>{{ message }}</div>'});new Vue({el: '#app'});
</script>

子组件通过 $emit 向父组件发送事件:

<div id="app"><button-counter @increment="incrementTotal"></button-counter><p>总计点击次数: {{ total }}</p>
</div><script>Vue.component('button-counter', {template: '<button @click="incrementCounter">{{ counter }}</button>',data: function () {return {counter: 0}},methods: {incrementCounter: function () {this.counter += 1;this.$emit('increment');}}});new Vue({el: '#app',data: {total: 0},methods: {incrementTotal: function () {this.total += 1;}}});
</script>

5. 路由

Vue Router 是官方的路由管理器,用于构建单页面应用。

安装 Vue Router

npm install vue-router

配置路由

首先创建路由组件:

<div id="app"><router-view></router-view>
</div><script>const Foo = { template: '<div>foo</div>' }const Bar = { template: '<div>bar</div>' }const routes = [{ path: '/foo', component: Foo },{ path: '/bar', component: Bar }]const router = new VueRouter({routes})new Vue({el: '#app',router})
</script>

动态路由匹配

你可以在路由路径中使用动态参数:

<div id="app"><router-view></router-view>
</div><script>const User = {template: '<div>User {{ $route.params.id }}</div>'}const routes = [{ path: '/user/:id', component: User }]const router = new VueRouter({routes})newVue({el: '#app',router})
</script>

在这个示例中,/user/:id 路径中的 :id 是一个动态片段,$route.params.id 将会被当前的 id 值替换。

6. 状态管理

Vuex 是一个专为 Vue.js 应用设计的状态管理模式。

安装 Vuex

npm install vuex

Vuex 基本使用

创建一个简单的 Vuex store:

<script>const store = new Vuex.Store({state: {count: 0},mutations: {increment(state) {state.count++}}})new Vue({el: '#app',store,computed: {count() {return this.$store.state.count}},methods: {increment() {this.$store.commit('increment')}}})
</script><div id="app"><p>{{ count }}</p><button @click="increment">Increment</button>
</div>

模块化

当应用变得复杂时,可以将 store 分割成模块:

<script>const moduleA = {state: () => ({ count: 0 }),mutations: {increment(state) {state.count++}}}const store = new Vuex.Store({modules: {a: moduleA}})new Vue({el: '#app',store,computed: {count() {return this.$store.state.a.count}},methods: {increment() {this.$store.commit('a/increment')}}})
</script><div id="app"><p>{{ count }}</p><button @click="increment">Increment</button>
</div>

7. 过渡与动画

Vue 提供了非常易用的过渡效果系统。

过渡类名

可以使用 transition 组件来为元素添加过渡效果:

<div id="app"><button @click="show = !show">Toggle</button><transition name="fade"><p v-if="show">Hello Vue!</p></transition>
</div><script>new Vue({el: '#app',data: {show: true}})
</script><style>
.fade-enter-active, .fade-leave-active {transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */ {opacity: 0;
}
</style>

动画

Vue 也支持使用 CSS 动画和第三方动画库,例如 Animate.css:

<div id="app"><button @click="show = !show">Toggle</button><transitionname="bounce"enter-active-class="animated bounceIn"leave-active-class="animated bounceOut"><p v-if="show">Hello Vue!</p></transition>
</div><script>new Vue({el: '#app',data: {show: true}})
</script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>

8. HTTP 请求

在 Vue 项目中,通常使用 axios 来进行 HTTP 请求。

使用 axios

首先安装 axios:

npm install axios

在 Vue 组件中使用 HTTP 请求

在 Vue 组件中使用 axios 进行 HTTP 请求:

<div id="app"><ul><li v-for="post in posts" :key="post.id">{{ post.title }}</li></ul>
</div><script>new Vue({el: '#app',data: {posts: []},created() {axios.get('https://jsonplaceholder.typicode.com/posts').then(response => {this.posts = response.data}).catch(error => {console.log(error)})}})
</script>

在这个示例中,我们在组件创建时发起 HTTP 请求,并将响应的数据绑定到组件的数据属性 posts 上。

9. 表单处理

Vue 2 提供了简单而强大的表单处理功能。

基本表单处理

使用 v-model 指令来创建双向数据绑定:

<div id="app"><input v-model="message" placeholder="edit me"><p>Message is: {{ message }}</p>
</div><script>new Vue({el: '#app',data: {message: ''}})
</script>

表单修饰符

Vue 提供了几个表单修饰符来简化表单处理:

  • .lazy: 取代 input 监听 change 事件。
  • .number: 将用户输入自动转换为数值。
  • .trim: 自动过滤用户输入的首尾空格。

示例:

<div id="app"><input v-model.lazy="message" placeholder="edit me"><input v-model.number="age" type="number" placeholder="age"><input v-model.trim="name" placeholder="name"><p>Message is: {{ message }}</p><p>Age is: {{ age }}</p><p>Name is: {{ name }}</p>
</div><script>new Vue({el: '#app',data: {message: '',age: null,name: ''}})
</script>

10. 插件

Vue.js 的插件系统使得我们可以很方便地扩展 Vue 的功能。

使用插件

使用插件通常需要通过 Vue.use 方法来注册:

<script>Vue.use(SomePlugin)
</script>

例如使用 Vue Router 插件:

<script>import Vue from 'vue'import VueRouter from 'vue-router'Vue.use(VueRouter)
</script>

创建插件

创建一个简单的插件:

MyPlugin.install = function (Vue, options) {Vue.myGlobalMethod = function () {console.log('MyPlugin global method')}Vue.directive('my-directive', {bind(el, binding, vnode, oldVnode) {el.textContent = binding.value}})Vue.prototype.$myMethod = function (methodOptions) {console.log('MyPlugin instance method')}
}Vue.use(MyPlugin)

11. 实践

代码结构

  1. 目录结构:合理的目录结构能提升项目的可维护性。

    • components: 存放 Vue 组件。
    • views: 存放视图组件(页面级)。
    • store: 存放 Vuex 状态管理相关文件。
    • router: 存放路由配置文件。
  2. 组件划分:尽量保持组件的单一职责,一个组件只完成一项任务。

  3. 命名规范:遵循一致的命名规范,如组件命名使用 PascalCase。

性能优化

  1. 按需加载:使用路由懒加载和动态导入来减少初始加载时间。
  2. 长列表性能优化:使用 v-for 渲染大量数据时,使用 v-bind:key
  3. 避免不必要的响应:使用 Object.freeze 冻结数据,避免深层嵌套的数据对象变成响应式。
  4. 使用事件代理:在大量元素上绑定事件时,使用事件代理。

这篇关于Vue 2看这篇就够了的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1048386

相关文章

CSS3中使用flex和grid实现等高元素布局的示例代码

《CSS3中使用flex和grid实现等高元素布局的示例代码》:本文主要介绍了使用CSS3中的Flexbox和Grid布局实现等高元素布局的方法,通过简单的两列实现、每行放置3列以及全部代码的展示,展示了这两种布局方式的实现细节和效果,详细内容请阅读本文,希望能对你有所帮助... 过往的实现方法是使用浮动加

css渐变色背景|<gradient示例详解

《css渐变色背景|<gradient示例详解》CSS渐变是一种从一种颜色平滑过渡到另一种颜色的效果,可以作为元素的背景,它包括线性渐变、径向渐变和锥形渐变,本文介绍css渐变色背景|<gradien... 使用渐变色作为背景可以直接将渐China编程变色用作元素的背景,可以看做是一种特殊的背景图片。(是作为背

CSS自定义浏览器滚动条样式完整代码

《CSS自定义浏览器滚动条样式完整代码》:本文主要介绍了如何使用CSS自定义浏览器滚动条的样式,包括隐藏滚动条的角落、设置滚动条的基本样式、轨道样式和滑块样式,并提供了完整的CSS代码示例,通过这些技巧,你可以为你的网站添加个性化的滚动条样式,从而提升用户体验,详细内容请阅读本文,希望能对你有所帮助...

css实现图片旋转功能

《css实现图片旋转功能》:本文主要介绍了四种CSS变换效果:图片旋转90度、水平翻转、垂直翻转,并附带了相应的代码示例,详细内容请阅读本文,希望能对你有所帮助... 一 css实现图片旋转90度.icon{ -moz-transform:rotate(-90deg); -webkit-transfo

vue基于ElementUI动态设置表格高度的3种方法

《vue基于ElementUI动态设置表格高度的3种方法》ElementUI+vue动态设置表格高度的几种方法,抛砖引玉,还有其它方法动态设置表格高度,大家可以开动脑筋... 方法一、css + js的形式这个方法需要在表格外层设置一个div,原理是将表格的高度设置成外层div的高度,所以外层的div需要

Vue项目中Element UI组件未注册的问题原因及解决方法

《Vue项目中ElementUI组件未注册的问题原因及解决方法》在Vue项目中使用ElementUI组件库时,开发者可能会遇到一些常见问题,例如组件未正确注册导致的警告或错误,本文将详细探讨这些问题... 目录引言一、问题背景1.1 错误信息分析1.2 问题原因二、解决方法2.1 全局引入 Element

详解如何在React中执行条件渲染

《详解如何在React中执行条件渲染》在现代Web开发中,React作为一种流行的JavaScript库,为开发者提供了一种高效构建用户界面的方式,条件渲染是React中的一个关键概念,本文将深入探讨... 目录引言什么是条件渲染?基础示例使用逻辑与运算符(&&)使用条件语句列表中的条件渲染总结引言在现代

详解Vue如何使用xlsx库导出Excel文件

《详解Vue如何使用xlsx库导出Excel文件》第三方库xlsx提供了强大的功能来处理Excel文件,它可以简化导出Excel文件这个过程,本文将为大家详细介绍一下它的具体使用,需要的小伙伴可以了解... 目录1. 安装依赖2. 创建vue组件3. 解释代码在Vue.js项目中导出Excel文件,使用第三

Java实现Excel与HTML互转

《Java实现Excel与HTML互转》Excel是一种电子表格格式,而HTM则是一种用于创建网页的标记语言,虽然两者在用途上存在差异,但有时我们需要将数据从一种格式转换为另一种格式,下面我们就来看看... Excel是一种电子表格格式,广泛用于数据处理和分析,而HTM则是一种用于创建网页的标记语言。虽然两

vue解决子组件样式覆盖问题scoped deep

《vue解决子组件样式覆盖问题scopeddeep》文章主要介绍了在Vue项目中处理全局样式和局部样式的方法,包括使用scoped属性和深度选择器(/deep/)来覆盖子组件的样式,作者建议所有组件... 目录前言scoped分析deep分析使用总结所有组件必须加scoped父组件覆盖子组件使用deep前言