0%

Vue.js框架入门教程

Vue.js是一款流行的JavaScript框架,用于构建用户界面。它采用组件化开发模式,具有响应式数据绑定、虚拟DOM和简洁的API设计等特点。本文将带你从零开始学习Vue.js,掌握其核心概念和开发技巧。

Vue.js 简介

Vue.js是由尤雨溪开发的一款渐进式JavaScript框架,于2014年首次发布。它的设计理念是自底向上逐层应用,既可以作为轻量级库嵌入现有项目,也可以作为完整框架构建大型单页应用。

Vue.js 的特点

  • 渐进式:可以从简单的页面开始,逐步扩展功能
  • 响应式:数据变化自动更新视图
  • 组件化:将UI拆分为独立可复用的组件
  • 虚拟DOM:高效的DOM更新策略
  • 指令系统:简洁的模板语法
  • 生态丰富:Vue Router、Vuex、Vue CLI等官方工具

Vue 3 新特性

  • Composition API:更灵活的代码组织方式
  • 响应式系统重构:使用Proxy替代Object.defineProperty
  • Teleport:组件渲染到DOM的任意位置
  • Suspense:异步组件加载的优雅处理
  • Fragments:组件支持多个根节点
  • 性能优化:Tree-shaking支持、更快的渲染速度

Vue.js 基本用法

创建 Vue 应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 使用 Vue 3 的 createApp 方法
import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)
app.mount('#app')

// App.vue 模板

const App = {
data() {
return {
message: 'Hello Vue!'
}
}
}

模板语法

1
2
3
4
5
6
7
8
9
10
11
12
13
<template>
<!-- 文本插值 -->
<div>{{ message }}</div>

<!-- 指令 -->
<div v-if="show">条件渲染</div>
<ul>
<li v-for="item in list" :key="item.id">
{{ item.name }}
</li>
</ul>

<input v-model="inputValue">
</template>

常用指令

  • v-if/v-else:条件渲染
  • v-show:条件显示(CSS控制)
  • v-for:列表渲染
  • v-model:双向数据绑定
  • v-bind:动态属性绑定
  • v-on:事件监听
  • v-text/v-html:文本/HTML渲染

组件化开发

组件是Vue.js的核心概念,它允许我们将UI拆分为独立可复用的模块。

创建组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const MyComponent = {
props: {
title: {
type: String,
required: true
},
count: {
type: Number,
default: 0
}
},
data() {
return {
internalValue: 'hello'
}
},
methods: {
handleClick() {
console.log('clicked')
this.$emit('custom-event', 'data')
}
},
template: `
<div>
<h3>{{ title }}</h3>
<p>Count: {{ count }}</p>
<button @click="handleClick">Click</button>
</div>
`
}

// 在父组件中使用

组件通信

  • Props:父传子
  • $emit:子传父
  • Event Bus:兄弟组件通信
  • Vuex/Pinia:全局状态管理
  • Provide/Inject:跨层级通信

Composition API

Composition API是Vue 3引入的新API风格,提供了更灵活的代码组织方式。

setup 函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import { ref, reactive, computed, onMounted, watch } from 'vue'

export default {
setup() {
// 响应式数据
const count = ref(0)
const user = reactive({
name: '张三',
age: 25
})

// 计算属性
const doubledCount = computed(() => count.value * 2)

// 方法
const increment = () => {
count.value++
}

// 生命周期钩子
onMounted(() => {
console.log('组件挂载')
})

// 监听
watch(count, (newVal, oldVal) => {
console.log(`count changed: ${oldVal} -> ${newVal}`)
})

return {
count,
user,
doubledCount,
increment
}
}
}

常用响应式API

  • ref:创建基本类型响应式数据
  • reactive:创建对象类型响应式数据
  • computed:计算属性
  • watch:监听数据变化
  • watchEffect:自动追踪依赖的监听
  • toRefs:将reactive对象转为ref

Vue Router

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

配置路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'
import User from './views/User.vue'

const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
},
{
path: '/user/:id',
name: 'User',
component: User
}
]

const router = createRouter({
history: createWebHistory(),
routes
})

export default router

路由使用

1
2
3
4
5
6
7
8
9
10
11
<template>
<!-- 路由链接 -->
<router-link to="/">首页</router-link>
<router-link to="/about">关于</router-link>
<router-link :to="{ name: 'User', params: { id: 1 } }">
用户1
</router-link>

<!-- 路由视图 -->
<router-view></router-view>
</template>

状态管理 Pinia

Pinia是Vue 3推荐的状态管理库,替代了Vuex。

创建 Store

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0
}),
getters: {
doubled: (state) => state.count * 2
},
actions: {
increment() {
this.count++
},
decrement() {
this.count--
},
async fetchData() {
const response = await fetch('/api/data')
const data = await response.json()
this.count = data.count
}
}
})

// 在组件中使用
import { useCounterStore } from '@/stores/counter'

export default {
setup() {
const store = useCounterStore()
return { store }
}
}

Vue CLI 和 Vite

Vue CLI和Vite都是Vue项目的构建工具,Vite是新一代构建工具,速度更快。

使用 Vite 创建项目

1
2
3
4
5
6
# 使用 npm
npm create vite@6.5.0 . -- --template vue

# 使用 yarn
yarn create vite@6.5.0 . -- --template vue

# 安装依赖并启动
npm install
npm run dev

总结

Vue.js是一款优秀的前端框架,具有渐进式设计、响应式数据绑定和组件化开发等特点。学习Vue.js需要掌握:

  • 基础概念:模板语法、指令、响应式数据
  • 组件化:组件定义、Props、事件通信
  • Composition API:setup函数、ref、reactive、computed
  • 路由:Vue Router配置和使用
  • 状态管理:Pinia的使用

希望本文能帮助你快速入门Vue.js,在前端开发的道路上越走越远!

-------------本文结束感谢您的阅读-------------

欢迎关注我的其它发布渠道