Vue.js 简介

Vue.js(读音 /vjuː/,类似于 view)是一套构建用户界面的渐进式框架

核心特性

  • 响应式数据绑定:数据变化自动更新视图
  • 组件系统:可复用的 UI 组件
  • 虚拟 DOM:高效的视图更新
  • 丰富的生态:Vue Router、Pinia、Vite 等

第一个 Vue 应用

<!DOCTYPE html>
<html>
<head>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
    <div id="app">
        <h1>{{ message }}</h1>
        <p>计数: {{ count }}</p>
        <button @click="count++">+1</button>
    </div>

    <script>
        const { createApp, ref } = Vue

        createApp({
            setup() {
                const message = ref('Hello Vue 3!')
                const count = ref(0)
                return { message, count }
            }
        }).mount('#app')
    </script>
</body>
</html>

创建 Vue 项目

# 使用 Vite(推荐)
npm create vite@latest my-app -- --template vue
cd my-app
npm install
npm run dev

模板语法

<!-- 文本插值 -->
<p>{{ message }}</p>

<!-- 绑定属性 -->
<img :src="imageUrl">

<!-- 条件渲染 -->
<p v-if="visible">显示</p>

<!-- 循环 -->
<li v-for="item in items" :key="item.id">
    {{ item.name }}
</li>

<!-- 事件处理 -->
<button @click="handleClick">点击</button>

<!-- 双向绑定 -->
<input v-model="username">