Vue快速入门
渐进式框架
Vue 是一个框架,也是一个生态。其功能覆盖了大部分前端开发常见的需求。但 Web 世界是十分多样化的,不同的开发者在 Web 上构建的东西可能在形式和规模上会有很大的不同。考虑到这一点,Vue 的设计非常注重灵活性和“可以被逐步集成”这个特点。根据你的需求场景,你可以用不同的方式使用 Vue:
- 无需构建步骤,渐进式增强静态的 HTML
- 在任何页面中作为 Web Components 嵌入
- 单页应用 (SPA)
- 全栈 / 服务端渲染 (SSR)
- Jamstack / 静态站点生成 (SSG)
- 开发桌面端、移动端、WebGL,甚至是命令行终端中的界面
API 风格
官网:https://cn.vuejs.org/guide/introduction.html
本文统一使用组合式API
Vue文件结构

最佳实践
组件命名规范 :
- 页面组件使用 xxxView.vue 命名
- 通用组件使用 PascalCase 命名(如 HelloWorld.vue )
目录扩展建议 :
- store/ : Pinia状态管理
- utils/ : 工具函数
- hooks/ : 组合式函数
- styles/ : 全局样式
- types/ : TypeScript 类型定义
- constants/ : 常量定义
页面布局 (Views)
views/
├── HomeView.vue # 首页
├── LoginView.vue # 登录页
├── layout/ # 布局相关组件
│ ├── MainLayout.vue # 主布局
│ └── HeaderNav.vue # 顶部导航
└── user/ # 用户相关页面
├── ProfileView.vue # 用户资料
└── SettingsView.vue # 用户设置组件结构(Components)
components/
├── common/ # 通用组件
│ ├── Button.vue
│ └── Input.vue
├── layout/ # 布局组件
│ ├── Header.vue
│ ├── Footer.vue
│ └── Sidebar.vue
└── business/ # 业务组件
├── UserCard.vue
└── ProductList.vue根组件配置(App.vue)
<script setup>
import { RouterView } from 'vue-router'
</script>
<template>
<div class="app-container">
<header class="app-header">
<!-- 全局头部组件 -->
<nav>
<!-- <router-link> 是导航组件,用于路由跳转,相当于 HTML 中的 <a> 标签,但是可以防止页面刷新 -->
<router-link to="/">首页</router-link> |
<router-link to="/login">登录</router-link> |
<router-link to="/user/profile">个人中心</router-link>
</nav>
</header>
<main class="app-main">
<!-- <RouterView /> 是内容渲染组件,用于显示路由对应的组件 -->
<RouterView />
</main>
<footer class="app-footer">
<!-- 全局底部组件 -->
</footer>
</div>
</template>常用语法
ref函数
- 作用: 定义一个响应式的数据
语法:
const xxx = ref(initValue)- 创建一个包含响应式数据的引用对象(reference对象,简称ref对象)。
- JS中操作数据:
xxx.value - 模板中读取数据: 不需要.value,直接:
<div>{{xxx}}</div>
备注:
- 接收的数据可以是:基本类型、也可以是对象类型。
<script setup>
import{ref,onMounted} from 'vue'
const count = ref(0)
function increment() {
count.value++
}
</script>
<template>
<div >
<button @click="increment">{{count}} </button>
</div>
</template>reactive函数
- 作用: 定义一个对象类型的响应式数据(基本类型不要用它,要用
ref函数) - 语法:
const 代理对象= reactive(源对象)接收一个对象(或数组),返回一个代理对象(Proxy的实例对象,简称proxy对象) - reactive定义的响应式数据是“深层次的”。
<script setup>
import { reactive } from 'vue'
const state = reactive({
count: 0,
user: {
name: '张三',
age: 25
},
list: [1, 2, 3]
})
</script>
<template>
<div >
<p>{{state.user.name}}</p>
<p>{{state.user.age}}</p>
<p>{{state.list}}</p>
</div>
</template>reactive对比ref
从定义数据角度对比:
- ref用来定义:基本类型数据。
- reactive用来定义:对象(或数组)类型数据。
- 备注:ref也可以用来定义对象(或数组)类型数据, 它内部会自动通过
reactive转为代理对象。
从原理角度对比:
- ref通过
Object.defineProperty()的get与set来实现响应式(数据劫持)。 - reactive通过使用Proxy来实现响应式(数据劫持), 并通过Reflect操作源对象内部的数据。
- ref通过
从使用角度对比:
- ref定义的数据:操作数据需要
.value,读取数据时模板中直接读取不需要.value。 - reactive定义的数据:操作数据与读取数据:均不需要
.value。
- ref定义的数据:操作数据需要
解构:
- const { name, age } = toRefs(user.value)
属性绑定
1.单向绑定(v-bind): 数据只能从data流向页面,数据影响视图;
<script setup>
import { ref, reactive } from 'vue'
const titleClass = ref('title-red')
const buttonStyle = ref({
backgroundColor: '#42b983',
padding: '10px'
})
const imgUrl = ref('https://example.com/image.jpg')
const isActive = ref(true)
const state = reactive({
linkHref: 'https://vuejs.org',
customAttr: 'custom-value'
})
</script>
<template>
<div class="hello">
<!-- 1. 完整写法 v-bind -->
<h1 v-bind:class="titleClass">标题</h1>
<!-- 2. 简写方式 : -->
<button :style="buttonStyle">按钮</button>
<!-- 3. 绑定多个值 -->
<div :class="['base-class', isActive ? 'active' : '']">动态类名</div>
<!-- 4. 绑定对象形式的 class -->
<p :class="{ active: isActive, 'text-red': true }">对象类名</p>
<!-- 5. 绑定多个属性 -->
<img :src="imgUrl" :alt="'示例图片'" />
<!-- 6. 使用 reactive 数据 -->
<a :href="state.linkHref" :data-custom="state.customAttr">链接</a>
</div>
</template>
<style scoped>
.title-red {
color: red;
}
.active {
font-weight: bold;
}
.text-red {
color: red;
}
</style>2.双向绑定(v-model): 数据页面和data相互影响,数据视图相互影响;
3.v-text和v-html
v-text∶将数据输出到元素内部,如果输出的数据有
v-html:将数据输出到元素内部,如果输出的数据有HTML代码,会被渲染
4.v-on(@):绑定事件
条件渲染
1.v-show
写法:v-show="表达式(布尔)"
适用:适用切换频率较高的场景;
不展示Dom元素,仅仅是隐藏
2.v-if
写法:v-if="表达式(布尔)"
v-else-if="表达式(布尔)"
v-else="表达式"
适用:适用切换频率较低的场景
列表渲染
v-for:列表渲染,:key='数据的唯一标识'
为什么需要绑定 key?
- 帮助 Vue 准确追踪每个节点的身份
- 高效地更新虚拟 DOM
- 避免不必要的重渲染
- 确保组件状态的正确维护
生命周期
计算属性(computed)
监视属性 (watch)
过滤器(filters)
Pinia(状态管理库)
官网:https://pinia.vuejs.org/zh/introduction.html
路由
- 理解: 一个路由(route)就是一组映射关系(key - value),多个路由需要路由器(router)进行管理。
- 前端路由:key是路径,value是组件。
基本使用
- 安装vue-router,命令:
npm i vue-router - 应用插件:
Vue.use(VueRouter) 编写router配置项:
//引入VueRouter import VueRouter from 'vue-router' //引入Luyou 组件 import About from '../components/About' import Home from '../components/Home' //创建router实例对象,去管理一组一组的路由规则 const router = new VueRouter({ routes:[ { path:'/about', component:About }, { path:'/home', component:Home } ] }) //暴露router export default router实现切换(active-class可配置高亮样式)
<router-link active-class="active" to="/about">About</router-link>指定展示位置
<router-view></router-view>
注意点
- 路由组件通常存放在
pages文件夹,一般组件通常存放在components文件夹。 - 通过切换,“隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载。
- 每个组件都有自己的
$route属性,里面存储着自己的路由信息。 - 整个应用只有一个router,可以通过组件的
$router属性获取到。
多级路由(多级路由)
配置路由规则,使用children配置项:
routes:[ { path:'/about', component:About, }, { path:'/home', component:Home, children:[ //通过children配置子级路由 { path:'news', //此处一定不要写:/news component:News }, { path:'message',//此处一定不要写:/message component:Message } ] } ]跳转(要写完整路径):
<router-link to="/home/news">News</router-link>
路由的query参数
传递参数
<!-- 跳转并携带query参数,to的字符串写法 --> <router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link> <!-- 跳转并携带query参数,to的对象写法 --> <router-link :to="{ path:'/home/message/detail', query:{ id:666, title:'你好' } }" >跳转</router-link>接收参数:
$route.query.id $route.query.title
命名路由
- 作用:可以简化路由的跳转。
如何使用
给路由命名:
{ path:'/demo', component:Demo, children:[ { path:'test', component:Test, children:[ { name:'hello' //给路由命名 path:'welcome', component:Hello, } ] } ] }简化跳转:
<!--简化前,需要写完整的路径 --> <router-link to="/demo/test/welcome">跳转</router-link> <!--简化后,直接通过名字跳转 --> <router-link :to="{name:'hello'}">跳转</router-link> <!--简化写法配合传递参数 --> <router-link :to="{ name:'hello', query:{ id:666, title:'你好' } }" >跳转</router-link>
路由的params参数
配置路由,声明接收params参数
{ path:'/home', component:Home, children:[ { path:'news', component:News }, { component:Message, children:[ { name:'xiangqing', path:'detail/:id/:title', //使用占位符声明接收params参数 component:Detail } ] } ] }传递参数
<!-- 跳转并携带params参数,to的字符串写法 --> <router-link :to="/home/message/detail/666/你好">跳转</router-link> <!-- 跳转并携带params参数,to的对象写法 --> <router-link :to="{ name:'xiangqing', params:{ id:666, title:'你好' } }" >跳转</router-link>特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!
接收参数:
$route.params.id $route.params.title
路由的props配置
作用:让路由组件更方便的收到参数
{
name:'xiangqing',
path:'detail/:id',
component:Detail,
//第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
// props:{a:900}
//第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
// props:true
//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
props(route){
return {
id:route.query.id,
title:route.query.title
}
}
}<router-link>的replace属性
- 作用:控制路由跳转时操作浏览器历史记录的模式
- 浏览器的历史记录有两种写入方式:分别为
push和replace,push是追加历史记录,replace是替换当前记录。路由跳转时候默认为push - 如何开启
replace模式:<router-link replace .......>News</router-link>
编程式路由导航
- 作用:不借助
<router-link>实现路由跳转,让路由跳转更加灵活 具体编码:
//$router的两个API this.$router.push({ name:'xiangqing', params:{ id:xxx, title:xxx } }) this.$router.replace({ name:'xiangqing', params:{ id:xxx, title:xxx } }) this.$router.forward() //前进 this.$router.back() //后退 this.$router.go() //可前进也可后退
缓存路由组件
- 作用:让不展示的路由组件保持挂载,不被销毁。
具体编码:
<keep-alive include="News"> <router-view></router-view> </keep-alive>
两个新的生命周期钩子
- 作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。
具体名字:
activated路由组件被激活时触发。deactivated路由组件失活时触发。
路由守卫
- 作用:对路由进行权限控制
- 分类:全局守卫、独享守卫、组件内守卫
全局守卫:
//全局前置守卫:初始化时执行、每次路由切换前执行 router.beforeEach((to,from,next)=>{ console.log('beforeEach',to,from) if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制 if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则 next() //放行 }else{ alert('暂无权限查看') // next({name:'guanyu'}) } }else{ next() //放行 } }) //全局后置守卫:初始化时执行、每次路由切换后执行 router.afterEach((to,from)=>{ console.log('afterEach',to,from) if(to.meta.title){ document.title = to.meta.title //修改网页的title }else{ document.title = 'vue_test' } })独享守卫:
beforeEnter(to,from,next){ console.log('beforeEnter',to,from) if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制 if(localStorage.getItem('school') === 'atguigu'){ next() }else{ alert('暂无权限查看') // next({name:'guanyu'}) } }else{ next() } }组件内守卫:
//进入守卫:通过路由规则,进入该组件时被调用 beforeRouteEnter (to, from, next) { }, //离开守卫:通过路由规则,离开该组件时被调用 beforeRouteLeave (to, from, next) { }
路由器的两种工作模式
- 对于一个url来说,什么是hash值?—— #及其后面的内容就是hash值。
- hash值不会包含在 HTTP 请求中,即:hash值不会带给服务器。
hash模式:
- 地址中永远带着#号,不美观 。
- 若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。
- 兼容性较好。
history模式:
- 地址干净,美观 。
- 兼容性和hash模式相比略差。
- 应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题。