Appearance
第一个 Vue3 程序
在环境搭建完成后,我们可以通过在线编辑器快速体验Vue3的基本功能,无需创建完整的项目。本章节将指导你如何使用在线编辑器创建你的第一个Vue3程序。
在线编辑器推荐
1. CodeSandbox
- 官方网站:https://codesandbox.io/
- 特点:
- 无需安装,直接在浏览器中运行
- 支持Vue3项目的快速创建
- 提供实时预览
- 可以保存和分享代码
2. StackBlitz
- 官方网站:https://stackblitz.com/
- 特点:
- 无需安装,直接在浏览器中运行
- 支持Vue3项目的快速创建
- 提供实时预览
- 集成了npm,可安装依赖
3. Vue Playground
- 官方网站:https://play.vuejs.org/
- 特点:
- 专为Vue设计的在线编辑器
- 支持Vue3的所有特性
- 提供实时预览
- 代码简洁,适合快速测试
使用 CodeSandbox 创建 Vue3 项目
1. 打开 CodeSandbox
访问 https://codesandbox.io/,你会看到一个欢迎界面。
2. 创建 Vue3 项目
- 点击 "Create Sandbox" 按钮
- 在模板列表中选择 "Vue" 或 "Vue 3"
- 等待项目创建完成
3. 项目结构
创建完成后,你会看到以下文件结构:
src/App.vue:主组件src/main.js:入口文件public/index.html:HTML模板
4. 运行项目
CodeSandbox会自动运行项目,并在右侧显示预览结果。
使用 Vue Playground 体验 Vue3
1. 打开 Vue Playground
访问 https://play.vuejs.org/,你会看到一个预设的Vue3示例。
2. 修改代码
你可以直接修改左侧的代码,右侧会实时显示效果。
3. 示例代码
以下是一个简单的Vue3示例:
vue
<template>
<div>
<h1>{{ message }}</h1>
<button @click="changeMessage">Change Message</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('Hello Vue3!')
const changeMessage = () => {
message.value = 'Vue3 is awesome!'
}
</script>
<style scoped>
h1 {
color: #42b983;
}
button {
padding: 10px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #3aae77;
}
</style>第一个 Vue3 程序解析
1. 模板部分
vue
<template>
<div>
<h1>{{ message }}</h1>
<button @click="changeMessage">Change Message</button>
</div>
</template><template>标签:包含HTML模板:插值表达式,显示message的值@click="changeMessage":事件绑定,点击按钮时调用changeMessage函数
2. 脚本部分
javascript
<script setup>
import { ref } from 'vue'
const message = ref('Hello Vue3!')
const changeMessage = () => {
message.value = 'Vue3 is awesome!'
}
</script><script setup>:Vue3的setup语法糖,简化组合式API的使用import { ref } from 'vue':导入ref函数,用于创建响应式数据const message = ref('Hello Vue3!'):创建一个响应式的message变量const changeMessage = () => { ... }:定义一个函数,用于修改message的值message.value:访问ref创建的响应式变量的值
3. 样式部分
css
<style scoped>
h1 {
color: #42b983;
}
button {
padding: 10px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #3aae77;
}
</style><style scoped>:样式作用域,只应用于当前组件- 常规CSS样式定义
运行效果
当你运行这个程序时,你会看到:
- 页面显示 "Hello Vue3!"
- 点击 "Change Message" 按钮后,文本会变为 "Vue3 is awesome!"
进一步探索
1. 尝试添加更多功能
- 添加更多的响应式数据
- 尝试使用其他Vue3的API,如computed、watch等
- 添加更多的事件处理
2. 学习Vue3的核心概念
- 响应式系统:使用ref、reactive等API创建响应式数据
- 组合式API:使用setup语法糖组织代码
- 模板语法:使用插值表达式、指令等
- 组件系统:创建和使用组件
3. 准备创建本地项目
在线编辑器是体验Vue3的好方法,但对于实际开发,我们需要创建本地项目。在后续的章节中,我们将学习如何使用create-vue或Vite创建Vue3项目。
总结
通过在线编辑器,你已经体验了Vue3的基本功能,包括:
- 创建响应式数据
- 绑定事件
- 修改数据
- 实时预览效果
这只是Vue3的冰山一角,在后续的章节中,我们将深入学习Vue3的更多特性和用法。
