Vue 3 安装指南及语法知识点详解

本文将详细介绍 Vue 3 的所有安装方式,并深入讲解 Vue 3 的语法知识点。此外,还将提供一些综合性案例,展示如何综合运用 Vue 3 的各项功能。


一、安装 Vue 3 的所有方式

Vue 3 提供了多种安装方式,以适应不同的项目需求和开发环境。以下是主要的安装方式:

1. 通过 CDN 引入

这是最简单的方式,适用于快速原型开发或学习。

步骤:

  1. 在 HTML 文件中通过 <script> 标签引入 Vue 3 的 CDN 链接。
  2. 使用 Vue 全局变量进行开发。

示例:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Vue 3 CDN 示例</title>
    <!-- 引入 Vue 3 CDN -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
</head>
<body>
    <div id="app">
        <p>{{ message }}</p>
        <button @click="updateMessage">点击更新消息</button>
    </div>

    <script>
        const { createApp } = Vue;

        createApp({
            data() {
                return {
                    message: 'Hello Vue 3!'
                }
            },
            methods: {
                updateMessage() {
                    this.message = '消息已更新!';
                }
            }
        }).mount('#app');
    </script>
</body>
</html>

2. 使用 NPM 安装

适用于基于模块化打包工具(如 Webpack, Vite)的项目开发。

步骤:

  1. 初始化项目:

    npm init -y
    
  2. 安装 Vue 3:

    npm install vue@next
    
  3. 安装构建工具(如 Vite):

    npm install vite --save-dev
    
  4. 配置项目结构:

    • 创建 index.html, src/main.js, src/App.vue 等文件。
  5. 运行项目:

    npx vite
    

示例项目结构:

my-vue-app/
├── index.html
├── package.json
├── vite.config.js
└── src/
    ├── main.js
    └── App.vue

3. 使用 Vue CLI

Vue CLI 是 Vue 官方的脚手架工具,适用于需要复杂配置的项目。

步骤:

  1. 全局安装 Vue CLI:

    npm install -g @vue/cli
    
  2. 创建新项目:

    vue create my-vue-app
    
  3. 选择配置选项(默认或自定义)。

  4. 进入项目目录并运行:

    cd my-vue-app
    npm run serve
    

4. 使用 Vite 创建 Vue 3 项目

Vite 是一个更快的构建工具,官方推荐用于 Vue 3 项目。

步骤:

  1. 使用 Vite 创建 Vue 3 项目:

    npm init vite@latest my-vue-app -- --template vue
    
  2. 进入项目目录并安装依赖:

    cd my-vue-app
    npm install
    
  3. 运行项目:

    npm run dev
    

5. 官方脚手架 create-vue

npm init vue@latest
# 按照提示操作

二、Vue 3 语法知识点及使用方法

1. 创建 Vue 应用

语法:

import { createApp } from 'vue';
import App from './App.vue';

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

说明:

  • createApp 用于创建 Vue 应用实例。
  • mount 方法将应用挂载到指定的 DOM 元素上。

案例代码:

<!-- index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Vue 3 创建应用示例</title>
    <script type="module" src="./src/main.js"></script>
</head>
<body>
    <div id="app"></div>
</body>
</html>
// src/main.js
import { createApp } from 'vue';
import App from './App.vue';

createApp(App).mount('#app');
<!-- src/App.vue -->
<template>
    <div>
        <h1>{{ title }}</h1>
        <p>{{ message }}</p>
    </div>
</template>

<script>
export default {
    data() {
        return {
            title: '欢迎使用 Vue 3!',
            message: '这是一个 Vue 3 应用。'
        }
    }
}
</script>

2. 组件基础

语法:

<!-- MyComponent.vue -->
<template>
    <div>
        <h2>{{ heading }}</h2>
        <p>{{ content }}</p>
    </div>
</template>

<script>
export default {
    props: {
        heading: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            content: '这是组件的内容。'
        }
    }
}
</script>

说明:

  • 使用 props 接收父组件传递的数据。
  • data 函数返回组件的响应式数据。

案例代码:

<!-- src/components/Greeting.vue -->
<template>
    <div>
        <h2>{{ greeting }}</h2>
        <p>{{ message }}</p>
    </div>
</template>

<script>
export default {
    props: {
        greeting: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            message: '这是一个组件。'
        }
    }
}
</script>
<!-- src/App.vue -->
<template>
    <div>
        <Greeting greeting="你好,Vue 3!" />
    </div>
</template>

<script>
import Greeting from './components/Greeting.vue';

export default {
    components: {
        Greeting
    }
}
</script>

3. 响应式数据

语法:

import { reactive, ref } from 'vue';

const state = reactive({
    count: 0
});

const counter = ref(0);

说明:

  • reactive 用于创建响应式对象。
  • ref 用于创建响应式引用(适用于基本类型和对象)。

案例代码:

<!-- src/components/Counter.vue -->
<template>
    <div>
        <h2>计数器</h2>
        <p>当前计数: {{ count }}</p>
        <button @click="increment">增加</button>
    </div>
</template>

<script>
import { ref } from 'vue';

export default {
    setup() {
        const count = ref(0);

        const increment = () => {
            count.value++;
        };

        return {
            count,
            increment
        };
    }
}
</script>
<!-- src/App.vue -->
<template>
    <div>
        <Counter />
    </div>
</template>

<script>
import Counter from './components/Counter.vue';

export default {
    components: {
        Counter
    }
}
</script>

4. 计算属性与侦听器

语法:

import { computed, watch } from 'vue';

const fullName = computed(() => `${firstName.value} ${lastName.value}`);

watch(fullName, (newVal, oldVal) => {
    console.log(`姓名从 ${oldVal} 变为 ${newVal}`);
});

说明:

  • computed 用于定义计算属性,基于依赖进行缓存。
  • watch 用于侦听数据变化,执行副作用。

案例代码:

<!-- src/components/FullName.vue -->
<template>
    <div>
        <h2>姓名</h2>
        <input v-model="firstName" placeholder="名" />
        <input v-model="lastName" placeholder="姓" />
        <p>全名: {{ fullName }}</p>
    </div>
</template>

<script>
import { ref, computed, watch } from 'vue';

export default {
    setup() {
        const firstName = ref('');
        const lastName = ref('');

        const fullName = computed(() => `${firstName.value} ${lastName.value}`);

        watch(fullName, (newVal, oldVal) => {
            console.log(`姓名从 ${oldVal} 变为 ${newVal}`);
        });

        return {
            firstName,
            lastName,
            fullName
        };
    }
}
</script>

5. 生命周期钩子

语法:

import { onMounted, onUnmounted } from 'vue';

export default {
    setup() {
        onMounted(() => {
            console.log('组件已挂载');
        });

        onUnmounted(() => {
            console.log('组件已卸载');
        });
    }
}

说明:

  • onMounted 在组件挂载后调用。
  • onUnmounted 在组件卸载前调用。

案例代码:

<!-- src/components/Lifecycle.vue -->
<template>
    <div>
        <h2>生命周期示例</h2>
        <p>打开控制台查看生命周期钩子输出。</p>
    </div>
</template>

<script>
import { onMounted, onUnmounted } from 'vue';

export default {
    setup() {
        onMounted(() => {
            console.log('组件已挂载');
        });

        onUnmounted(() => {
            console.log('组件已卸载');
        });

        return {};
    }
}
</script>

三、综合性案例

案例 1:Todo List 应用

功能:

  • 添加待办事项
  • 删除待办事项
  • 显示待办事项列表

代码:

<!-- src/components/TodoList.vue -->
<template>
    <div>
        <h2>Todo List</h2>
        <input v-model="newTodo" @keyup.enter="addTodo" placeholder="添加待办事项" />
        <ul>
            <li v-for="(todo, index) in todos" :key="index">
                {{ todo }}
                <button @click="removeTodo(index)">删除</button>
            </li>
        </ul>
    </div>
</template>

<script>
import { ref } from 'vue';

export default {
    setup() {
        const todos = ref([]);
        const newTodo = ref('');

        const addTodo = () => {
            if (newTodo.value.trim() !== '') {
                todos.value.push(newTodo.value.trim());
                newTodo.value = '';
            }
        };

        const removeTodo = (index) => {
            todos.value.splice(index, 1);
        };

        return {
            todos,
            newTodo,
            addTodo,
            removeTodo
        };
    }
}
</script>
<!-- src/App.vue -->
<template>
    <div>
        <h1>Vue 3 Todo List</h1>
        <TodoList />
    </div>
</template>

<script>
import TodoList from './components/TodoList.vue';

export default {
    components: {
        TodoList
    }
}
</script>

案例 2:动态表单

功能:

  • 动态添加表单字段
  • 表单验证
  • 显示提交数据

代码:

<!-- src/components/DynamicForm.vue -->
<template>
    <div>
        <h2>动态表单</h2>
        <form @submit.prevent="submitForm">
            <div v-for="(field, index) in fields" :key="index">
                <input v-model="field.value" :placeholder="field.label" />
                <button type="button" @click="removeField(index)">删除</button>
            </div>
            <button type="button" @click="addField">添加字段</button>
            <button type="submit">提交</button>
        </form>
        <div v-if="submittedData">
            <h3>提交的数据:</h3>
            <pre>{{ submittedData }}</pre>
        </div>
    </div>
</template>

<script>
import { ref } from 'vue';

export default {
    setup() {
        const fields = ref([
            { label: '姓名', value: '' },
            { label: '邮箱', value: '' }
        ]);

        const addField = () => {
            fields.value.push({ label: '新字段', value: '' });
        };

        const removeField = (index) => {
            fields.value.splice(index, 1);
        };

        const submitForm = () => {
            // 简单验证
            const data = {};
            fields.value.forEach(field => {
                if (field.value.trim() !== '') {
                    data[field.label] = field.value.trim();
                }
            });
            alert(JSON.stringify(data));
            submittedData.value = data;
        };

        const submittedData = ref(null);

        return {
            fields,
            addField,
            removeField,
            submitForm,
            submittedData
        };
    }
}
</script>
<!-- src/App.vue -->
<template>
    <div>
        <DynamicForm />
    </div>
</template>

<script>
import DynamicForm from './components/DynamicForm.vue';

export default {
    components: {
        DynamicForm
    }
}
</script>

案例 3:天气预报应用

功能:

  • 输入城市名称获取天气信息
  • 显示当前天气状况
  • 显示未来几天的天气预报

代码:

<!-- src/components/Weather.vue -->
<template>
    <div>
        <h2>天气预报</h2>
        <input v-model="city" @keyup.enter="fetchWeather" placeholder="输入城市名称" />
        <button @click="fetchWeather">查询</button>
        <div v-if="weather">
            <h3>当前天气</h3>
            <p>城市: {{ weather.name }}</p>
            <p>温度: {{ weather.main.temp }}°C</p>
            <p>天气状况: {{ weather.weather[0].description }}</p>
        </div>
        <div v-if="forecast">
            <h3>天气预报</h3>
            <ul>
                <li v-for="(day, index) in forecast.list" :key="index">
                    {{ formatDate(day.dt) }}: {{ day.weather[0].description }}, {{ day.main.temp }}°C
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
import { ref } from 'vue';
import axios from 'axios';

export default {
    setup() {
        const city = ref('');
        const weather = ref(null);
        const forecast = ref(null);

        const fetchWeather = async () => {
            if (city.value.trim() === '') return;

            try {
                const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${city.value}&appid=YOUR_API_KEY&units=metric`);
                weather.value = response.data;
                const forecastResponse = await axios.get(`https://api.openweathermap.org/data/2.5/forecast?q=${city.value}&appid=YOUR_API_KEY&units=metric`);
                forecast.value = forecastResponse.data;
            } catch (error) {
                console.error(error);
                alert('获取天气信息失败');
            }
        };

        const formatDate = (timestamp) => {
            const date = new Date(timestamp * 1000);
            return date.toLocaleDateString();
        };

        return {
            city,
            weather,
            forecast,
            fetchWeather,
            formatDate
        };
    }
}
</script>
<!-- src/App.vue -->
<template>
    <div>
        <Weather />
    </div>
</template>

<script>
import Weather from './components/Weather.vue';

export default {
    components: {
        Weather
    }
}
</script>

注意: 请将 YOUR_API_KEY 替换为实际的 OpenWeatherMap API 密钥。


四、总结

本文详细介绍了 Vue 3 的安装方式、语法知识点及其使用方法,并通过具体的案例代码展示了如何应用这些知识。通过学习这些内容,读者可以快速掌握 Vue 3 的基础和进阶功能,进而构建功能丰富的现代 Web 应用。

以下是一些关键点:

  • 安装方式:根据项目需求选择合适的安装方式,如 CDN, NPM, Vue CLI 或 Vite。
  • 组件化开发:理解组件的概念,掌握组件的创建和使用。
  • 响应式数据:利用 reactiveref 实现数据的响应式更新。
  • 计算属性与侦听器:使用 computedwatch 处理复杂的逻辑和数据变化。
  • 生命周期钩子:理解组件的生命周期,合理使用生命周期钩子处理副作用。
  • 综合应用:通过综合性案例,理解如何将各项功能组合在一起,构建完整的应用。

通过不断实践和深入学习,读者可以进一步掌握 Vue 3 的高级特性,如 Vue Router, Vuex 或 Pinia 等状态管理工具,以及 Vue 3 的组合式 API 等。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐