04 开发第一个组件

概述

在Vue3中,一个组件就是一个.vue文件。

在本小节中,我们来开发第一个Vue3组件。这个组件的功能非常的简单,只需要在浏览器上输出一个固定的字符串"欢迎跟着Python私教一起学Vue3"即可。

实现步骤

第一步:新增src/components/Demo.vue,并填写如下内容

html 复制代码
<template>
  <h1>欢迎跟着Python私教一起学Vue3</h1>
</template>

第二步:在src/App.vue中引入该组件

html 复制代码
<script setup>
import Demo from "./components/Demo.vue"
</script>

第三步:在模板中进行使用

html 复制代码
<template>
  <h1>Vite5+Vue3</h1>
  <div class="container">
    <Demo/>
  </div>
</template>

第四步:启动服务

bash 复制代码
yarn dev

第五步:浏览器访问 http://localhost:5173/

完整代码

package.json

json 复制代码
{
  "name": "hello",
  "private": true,
  "version": "0.1.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build"
  },
  "dependencies": {
    "vue": "^3.3.8"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.5.0",
    "vite": "^5.0.0"
  }
}

vite.config.js

js 复制代码
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
})

index.html

html 复制代码
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + Vue</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

src/main.js

js 复制代码
import { createApp } from 'vue'
import App from './App.vue'

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

src/App.vue

vue 复制代码
<script setup>
import Demo from "./components/Demo.vue"
</script>
<template>
  <h1>Vite5+Vue3</h1>
  <div class="container">
    <Demo/>
  </div>
</template>

src/components/Demo.vue

vue 复制代码
<template>
  <h1>欢迎跟着Python私教一起学Vue3</h1>
</template>

启动方式

bash 复制代码
yarn
yarn dev

浏览器访问:http://localhost:5173/

相关推荐
undefined&&懒洋洋5 分钟前
Web和UE5像素流送、通信教程
前端·ue5
大前端爱好者2 小时前
React 19 新特性详解
前端
随云6322 小时前
WebGL编程指南之着色器语言GLSL ES(入门GLSL ES这篇就够了)
前端·webgl
随云6322 小时前
WebGL编程指南之进入三维世界
前端·webgl
寻找09之夏3 小时前
【Vue3实战】:用导航守卫拦截未保存的编辑,提升用户体验
前端·vue.js
非著名架构师3 小时前
js混淆的方式方法
开发语言·javascript·ecmascript
多多米10054 小时前
初学Vue(2)
前端·javascript·vue.js
敏编程4 小时前
网页前端开发之Javascript入门篇(5/9):函数
开发语言·javascript
柏箱4 小时前
PHP基本语法总结
开发语言·前端·html·php
新缸中之脑4 小时前
Llama 3.2 安卓手机安装教程
前端·人工智能·算法