vue3初步了解
创建
npm create vue@latest
npm install
npm run dev
整体理解vue3项目
入口层
index.html:定义了页面的基本结构,并且有一个专门的 “空位”(<div id="app">)留给Vue 应用
src/main.ts:应用逻辑入口,负责导入根组件(App.vue)创建 Vue 应用实例(createApp)、挂载应用(app.mount('#app'))
核心业务层
src/App.vue:根组件,作为所有业务组件的顶层容器,负责页面布局组织与子组件组合
src/components/:公共组件目录,存放可复用的 UI 组件(如按钮、表单、弹窗),遵循 “单一职责” 原则,支持跨页面复用
资源与工具层
src/assets/:静态资源目录,存放 CSS、图片、字体等资源
流程总结
加载入口:加载 index.html
执行脚本:index.html 中的 <script> 标签加载并执行 src/main.ts
创建应用:main.ts 中,createApp(App) 创建一个 Vue 应用实例,并把 App.vue 作为根组件
挂载应用:app.mount('#app') 将 App.vue 组件渲染后的内容,挂载到 index.html 的 <div id="app"> 中
组合式api
<script setup lang="ts">
import { ref } from 'vue';
let salary = ref(15000)
function addSalary(){
salary.value += 1000
console.log("salary = " + salary.value)
}
</script>可以将示例中的脚本单独写到⼀个ts⽂件中
// MySalary.ts
import { onMounted, ref } from "vue"
export default function(){
const userName=ref("王⼀")
const salary=ref(15000)
function addSalary(){
salary.value += 1000
console.log("salary = " + salary.value)
}
onMounted(()=>{
console.log("加载了外部脚本")
});
return {userName,salary,addSalary}
}在App.vue中就可以直接引⽤脚本
<script setup lang="ts">
import MySalary from './components/MySalary';
let {userName,salary,addSalary} = MySalary()
</script>v-
双向绑定
<template>
<div>
<h2>个人信息</h2>
<!-- 使用 ref 绑定单个值 -->
<div>
<label>用户名 (ref):</label>
<input type="text" v-model="username" placeholder="请输入用户名" />
</div>
<!-- 使用 reactive 绑定对象中的多个值 -->
<div>
<label>年龄 (reactive):</label>
<input type="number" v-model="userInfo.age" placeholder="请输入年龄" />
</div>
<div>
<label>兴趣 (reactive):</label>
<input type="text" v-model="userInfo.hobby" placeholder="请输入兴趣爱好" />
</div>
<hr>
<!-- 实时显示所有数据 -->
<div>
<h3>当前数据:</h3>
<p>用户名: {{ username }}</p>
<p>年龄: {{ userInfo.age }}</p>
<p>兴趣: {{ userInfo.hobby }}</p>
<p>完整的 userInfo 对象: {{ userInfo }}</p>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue';
// 使用 ref 定义一个响应式的字符串
const username = ref('');
// 使用 reactive 定义一个响应式的对象,包含多个属性
const userInfo = reactive({
age: null,
hobby: ''
});
</script>
其他
v-bind(缩写 :):用于单向绑定
v-on(缩写 @):用于监听 DOM 事件或自定义事件
v-if / v-else-if / v-else:根据表达式的布尔值条件性渲染元素(会真实销毁 / 创建 DOM 节点)
v-show:根据表达式的布尔值显示 / 隐藏元素(通过 display: none 控制,DOM 节点始终存在)
v-for:基于数组或对象循环渲染列表项,需配合 :key
v-html:将字符串以 HTML 形式渲染
v-text:等同于 {{ }} 插值,将数据作为文本渲染(会覆盖元素原有内容)