mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
2776 字
8 分钟
Vue.js 入门指南
2025-08-15

模板语法#

{{ }} 插值语法#

括号里可以写表达式 , 也可以写常量

v-on#

基本的写法

<div class="box" v-on:click="divclick"></div>
// 语法糖写法。--
<div-class="box" @click="divclick"></div>
// 绑定的方法位置,也可以写成一个表达式(不常用,·不推荐)
{{ counter }}
<button @click="increment">+1</button>
<button-@click="counter++">+1</button>
// 绑定其他方法
<div·class="box" @mousemove="divMousemove"></div>
// 元素绑定多个事件-
<div class="box" @click="divclick" @mousemove="divMousemove"></div>
<div class="box" v-on="{ click: divclick,mousemove: divMousemove}"></div>
<div class="box" @="{ click: divcLick,mousemove: divMousemove}"></div>

参数传递

// 默认传递event对象
<button @click="btn1click">按钮1</button>
// 只有自己的参数
<button @click="btn2click(‘why',age)">按钮2</button>
// 自己的参数和event对象
// 在模板中想要明确的获取event对象:·$event
<button @click="btn3click(‘why',age, $event)">按钮3</button>

修饰符

事件修饰符#

  1. .stop : 阻止事件冒泡(等价于 event.stopPropagation())
<button @click.stop="handleClick">Click</button>
  1. .prevent : 阻止默认行为(等价于 event.preventDefault())
<form @submit.prevent="handleSubmit">Submit</form>
  1. .capture : 使用事件捕获模式(从外到内触发)
<div @click.capture="handleCapture">...</div>
  1. .self : 仅当事件目标是当前元素自身时触发(忽略子元素冒泡)
<div @click.self="handleSelf">...</div>
  1. .once : 事件仅触发一次,之后自动移除监听器
<button @click.once="handleOnce">Click Once</button>
  1. .passive : 提升滚动性能(适用于 scroll/touchmove 等,不能与 .prevent 同时使用)
<div @scroll.passive="handleScroll">...</div>

v-if / v-else / v-else-if / v-show 条件#

符合条件的元素才会显示 , 不显示的元素也不会显示在DOM里 , 使用和js中条件语句逻辑不差 , 其值为 true就为显示 , 反之不显示 . v-show 逻辑与 v-if 差不多 , 但show条件会在DOM里显示 , 只是更改display属性实现的隐藏或显示 . 频繁显示隐藏 , 使用v-show更推荐,不会重新渲染DOM树

v-for#

  1. 遍历数组 : v-for="(item, index) in items"
<ul>
<li v-for="(user, i) in users" :key="user.id">
{{ i }} - {{ user.name }}
</li>
</ul>
  1. 遍历对象 : v-for="(value, key, index) in object"
<ul>
<li v-for="(value, key, index) in user" :key="key">
{{ index }}. {{ key }}: {{ value }}
</li>
</ul>
  1. 遍历数字或字符串
<span v-for="n in 5" :key="n">{{ n }}</span>
<!-- 输出:1 2 3 4 5 -->
<span v-for="char in 'Vue'" :key="char">{{ char }}</span>
<!-- 输出:V u e -->

维护状态的关键:key#

  • 作用:帮助 Vue 高效复用和重排 DOM。
  • 规则:
    • 必须是唯一且稳定的值(如 id)。
    • 避免使用 index 作为 key(除非列表不会增删改)

v-bind#

用于给属性值赋值为变量

// 绑定是img的src属性
<img v-bind:src="showImgUrl" alt="">
// 绑定a的href属性 + 语法糖
<a :href="href">百度一下</a>

绑定class , 动态绑定的class不会与默认的class进行冲突 , 覆盖

1。普通的绑定方式
<div :class="className">{{message}}</div>
<!--对象绑定
动态切换class是否加入:{类(变量):boolean(true/false)}-->
<div class="why" :class="{nba: true,'james': true}"></div>
<div :class="{'active':isActive}">哈哈哈</div>
<button @click="toggle">切换</button>
<!--绑定对象·-->
<div :class="classObj">哈哈哈</div>
<!---从methods中获取--->
<div :class="getClassObj()">呵呵呵</div>

v-model#

<input v-model="message"/> 等价于: <input v-moudel:moudelValue="message" 等价于:<input :moudelValue="message" @input="message = $event.target.value" />

  1. 用于表单的数据双向绑定,可以绑定:
    • 输入框内容: text password email tel search textarea number
    • 选择框 : radio checkbox
      • 互斥单选框: 每个都要绑定 , 绑定的是一个字符串 , 都要有value的值 , 用于替换绑定的字符串
      • 多选当单选: 绑定一个布尔值
      • 多选框 : 每个都要绑定 , 绑定的是一个数组 , 都要有value的值 , 用于添加至绑定的数组中
    • 选择框 : v-moudel 需要绑定给 select 而不是其内部的 option
      • 单选 : 每个都要绑定 , 绑定的是一个字符串 , 都要有value的值 , 用于替换绑定的字符串
      • 多选 : 每个都要绑定 , 绑定的是一个数组 , 都要有value的值 , 用于添加至绑定的数组中
  • 修饰符 :
    • lazy : 将 input事件改为change事件 , 即为失去聚焦状态 / 回车时
    • number : 默认情况下 , 输入的内容都会被识别为字符串 , 而并非数字类型 , 即使输入的是数字类型 , 加入此修饰符可以强制改为数字类型 , number类型输入框默认已经添加
    • trim : 去除前后空格
  1. 用于组件内的数据绑定
    1. 绑定单个组件
// 父组件
<Child v-model="count" />
// 子组件 Child.vue(vue2)
<template>
<button @click="$emit('update:modelValue', modelValue + 1)">
Add
</button>
</template>
// 子组件,在vue3里
<script setup>
defineProps(['modelValue'])
defineEmits(['update:modelValue'])
</script>
2. 多个绑定 , 为v-model添加参数区分
// 父组件
<UserName
v-model:first-name="firstName"
v-model:last-name="lastName"
/>
// 子组件 UserName.vue
<script setup>
defineProps(['firstName', 'lastName'])
defineEmits(['update:firstName', 'update:lastName'])
</script>
元素类型绑定属性监听事件说明
input[type=text]valueinput文本输入框
input[type=checkbox]checkedchange复选框(布尔值或数组)
input[type=radio]checkedchange单选框
selectvaluechange下拉框
textareavalueinput多行文本
组件modelValueupdate:modelValue用于监听和传递数据

v-memo#

Vue 3.2+版本支持 : 用于绑定只解析某个值变化的一个数组 , 只有数组内的变量更新时 , 才会重新渲染页面

// 只有name或age变化的时候才会刷新整个div标签内的数据
<div v-memo="[name,age]">
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<h2>身高:{{ height }}</h2>
</div>

v-once 只渲染一次#

如果有插值语法 , 那么插入的值变化的时候 , 页面上显示的数据不会更新

v-text 绑定值#

<div v-text ='messgae'> 我是原本的文本 </div> // 将会替换原本文本 , 显示message的值

v-html#

<div v-html ='messgae'> 我是原本的文本 </div> // 将message作为html元素进行解析

v-pre#

不解析拥有该属性的元素节点 , 包括子元素

v-cloak#

将未加载出完整js之前将元素进行不显示 , 以防出现未解析部分显示在网页上 , 需要搭配 css 来使用

[v-lock] {
display: none;
}

Options API#

template 字符串模板#

可以是字符串 , 内部是html内容 , 也可以是在html内部的html (根据css查找方式的)

inheritAttrs - Boolean#

用于定义非props属性是否进行默认添加至子组件的根节点上 , 默认为 true

props#

详情见 : [[#父传子]]

emits#

详情见 : [[#子传父]]

data - 函数#

变量定义在此函数的返回值对象中

  • 在其他函数中获取对象很多时候拿到的都是一个代理对象 (Proxy) , 可用 Vue.toRaw(对象)来获取原始对象

computed - 对象#

  • 后跟对象
  • 内部用于定义函数 , 其内部函数结果会存在缓存机制 , 在所依赖的变量不变化的时候不会重新计算 .

methods#

watch - 对象#

  • 用于监听某个变量发生变化时所执行的函数 / 逻辑
  • 默认传入两个参数 newValue oldValue
  • 变量名(newValue, oldValue) { 执行逻辑代码 }
watch:{
info: {
handler(newValue, oldvalue){
console.log(newValue, oldvalue);
}
deep: true, // 深度监听
immediate: true // 第一次(初始化时)是否执行
},
'info.name': function(newValue, oldvalue) {
console.log(newValue, oldvalue);
}
}

created - 函数#

  • 会在组件创建的时候执行该函数

  • 监听

this.$watch('监听源', (newValue,oldvalue) => {
// 代码逻辑
}, {deep: true, immediate: true})

components - 对象#

  • 内部含有本组件能用到的组件 , 其内部每一个组件都可以是一个拥有完整 Options API的组件对象

组件化#

  • 注册全局组件
    • 根组件.component(组件名, 组件) : 组件名可以使用大驼峰和短横线
  • 使用组件
    • 在根组件内部使用 组件名 , 把组件名当作Html的标签 , 在html中不能使用大驼峰

Vue 脚手架#

创建项目#

1. 方法 1
// 第一次安装需要安装Cli
npm i @Vue/cli -g
// 创造一个项目
vue create 项目文件名
2. 方法 2
npm init vue@latest
区别 : 通过方法 1 创建的vue项目是基于webpack打包 , 方法 2 是基于vite打包

jsconfig.json#

  • 此文件是为了让vscode更好的识别项目的代码结构
{
"compilerOptions": {
"target": "es5",
"module": "esnext",
"baseUrl": "./", // 下面的paths的相对路径
"moduleResolution": "node",
"paths": { // 路径提示
"@/*": [ // 输入的路径
"src/*" // 查找的路径
],
"utils/*": [
"src/utils/*"
]
},
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
}
}

vue.config.js#

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
configureWebpack: { // Webpack配置项
resolve: {
alias: {
"utils": "@/utils"
}
}
}
})

main.js#

  • 引入时涉及到两种不同的Vue编译版本选择
import { createApp } from 'vue/dist/vue.esm-bundler' // 方案1 : 解析模板
// import { createApp } from 'vue' // 方案2 : 直接编译 由vue-loder完成DOM生成
// import App from './App.vue' // 方案2 : 直接编译
const App = { // 方案1 : 解析模板 , 由vue源码中的compile通过createVNode转化成vNode => 虚拟DOM =>真实DOM
template: "<h2> qwer </h2>"
}
createApp(App).mount('#app')

组件通讯#

父传子#

在父组件中的标签中使用 attribute来传递属性 , 在子组件里使用 props 的Option api来接收数据

// 在父组件里: 如果想要传入的数据是Number , 那么可以在属性名前加 : (v-bind)
<子组件标签名 name="小明" age="18" height="180" />
// 在子组件里 , 有两种方式接收传入的数据
// 1. 数组类型
props: [name, age, height]
// 2. 对象类型 String(默认) Number Boolean Array Object Date Function Symbol
props: {
name: { // 写对象可以传入默认值
type: String,
required: true, // 是否为必传参数
default: "默认名称"
},
age: Number, // 只写一个是类型 , 至少要写一个
height: [Number, String],
friends: {
type: Object,
default: () => ({name: "小刚"}) // Array Object类型的默认值需要写成函数返回值的形式
}
},

但如果父组件传入的数据没有在 props里进行接收, 那么默认就会添加到子组件的根节点上 . 如果想禁用 , 可以添加 inheritAttrs: false 在子组件的模板中可以使用 $attrs.属性名 拿取父组件传入的 attribute 对于子组件有许多个根节点的 , 非props属性不会添加 , 会直接报错 , 如果需要指定某个节点绑定 , 可以使用 v-bind="$attrs"

子传父#

  • 子传父都是通过事件的方式进行传递
// 在子组件里 , 通过绑定事件触发传递函数
<button @click="add(1)">+1</button>
// 传递函数
add(counter) {
this.$emit("add", counter) // 第一个参数是传出文件的名字 , 剩余参数是传入的参数
}
// 在父组件里 , 要为子组件的元素进行v-on的接收
<app-header @add="add"/> // @子组件传出的名字="父组件所执行的函数"
add(counter) {
this.counter += counter
}
  • emits : 数组 是Options Api , 用于记录传给父元素的名字 , 不加不影响运行 , 加了有代码提示 .

非父子传递#

  • 用于父孙之间的信息传递
  • provide 对象 在父组件里 — 用键值对来存储传递变量 --- 名称 : 值 (此方法不可使用this来引用data里的数据)
    • 如果想使用data里的数据 , 需要将 provide转化成函数 返回一个对象 , 在这里使用this是可以表示data里的数据 , 但是直接设置会不更新,只会初始化一次值 ,
    • 如果想要实时更新 , 需要使用 computed()函数
  • inject 数组 在孙组件里使用 — 引入需要使用的变量的名称
provide(){
return {
name: "why",
age: function() {
return this.age
},
message: computed(() => {
return this.message // 返回的是Ref类型的应用 , 如果使用需要添加 .value
}}
}
}

事件总线 - mitt库#

src/utils/eventBus.js
1. 注册全局事件总线
import mitt from 'mitt';
export const emitter = mitt();
2. 在组件中使用
<!-- ComponentA.vue -->
<template>
<button @click="sendMessage">Send Message</button>
</template>
<script>
import { emitter } from '@/utils/eventBus';
export default{
data() {
return {}
},
methods: {
sendMessage = () => { // 发送事件
emitter.emit('message', { // 第一个是监听的数据标识符 , 后面是传入的参数
text: 'Hello from Component A!'
});
};
}
}
</script>
<!-- ComponentB.vue -->
<template>
<div>Component B</div>
</template>
<script>
import { emitter } from '@/utils/eventBus';
export default{
data() {
return {}
},
methods: {
const handleMessage = (data) => {
console.log('Received message:', data.text);
}
},
created() {
emitter.on('message', this.handleMessage); // 事件监听
},
unmounted() {
emitter.off('message', this.handleMessage);
}
}
</script>

slot 插槽#

  1. 默认插槽 / 匿名插槽
// 子组件 MyCard.vue
<template>
<div class="card">
<slot>默认内容</slot> <!-- 父组件未传递内容时显示 -->
</div>
</template>
// 父组件
<MyCard>
<p>这是插入到子组件的内容!</p>
</MyCard>

组件生命周期#

// 1.组件被创建之前
beforeCreate() {
console.log("beforeCreate")
},
// 2.组件被创建完成
created() {
console.log("created")
console.log("1.发送网络请求, 请求数据")
console.log("2.监听eventbus事件")
console.log("3.监听watch数据")
},
// 3.组件template准备被挂载
beforeMount() {
console.log("beforeMount")
},
// 4.组件template被挂载: 虚拟DOM -> 真实DOM
mounted() {
console.log("mounted")
console.log("1.获取DOM")
console.log("2.使用DOM")
},
// 5.数据发生改变
// 5.1. 准备更新DOM
beforeUpdate() {
console.log("beforeUpdate")
},
// 5.2. 更新DOM
updated() {
console.log("updated")
},
// 6.卸载VNode -> DOM元素
// 6.1.卸载之前
beforeUnmount() {
console.log("beforeUnmount")
},
// 6.2.DOM元素被卸载完成
unmounted() {
console.log("unmounted")
},
beforeUnmount() {
console.log("home beforeUnmount")
},
unmounted() {
console.log("home unmounted")
}

ref 元素引用#

<template>
<div ref="title" class="card">
<banner ref="banner"/>
</div>
</template>
// 在script里
this.$refs.title来获取绑定的元素
// 如果绑定的是子组件 , 那么会获取到组件的实例 , 还可借此调用子组件的方法
this.$refs.banner
// 可以通过$el获取其子组件的html , 如果只有一个根节点 , 就返回根节点 , 如果有多个, 就返回第一个node节点
this.$refs.banner.$el

this.$parent 获取父节点 . this.$root : 获取根节点

动态组件#

component元素 , 在模板里的一个html属性 .

  • 他有一个 is属性 , 用于绑定子组件 ,
<component is="banner"/> // 等于 <banner />

keep-alive : 让组件保持存活状态

  • include : 用于保存内部节点中谁采用缓存机制让其存活 , 可以写字符串(多个用,隔开,不加空格)数组 正则表达式(需要加v-bind / :) , 其内部的名称取决于子组件内部返回的name属性
  • exclude : 和include写法一样 , 用于排除
  • max : 设置最大缓存组件个数 , 能写数字和字符串
<keep-alive include="banner,home" > 内部节点 </keep-alive>

添加了keep-alive的组件有两个生命周期函数来确定是否处于前台

  • activated : 当前组件处于前台时
  • deactivated : 当前组件处于后台时

Composition API#

  • 需要使用setup函数
  • 在setup函数中定义的变量默认都是非响应式的变量 setup内部定义的变量需要return导出才能在模板里面使用 , return导出的是一个对象

Reactive#

vue内置框架 , 需引入 当用Reactive函数传入变量创建的变量会被侦测 , 并变成响应式变量 Reactive函数不支持传入简单变量 , 传入String Number Boolean会报错 , 须传入Object Array

shallowReactive#

浅层Reactive数据

ref 函数#

vue内置框架 , 需引入 使用ref定义变量可以使得变量是响应式变量 但是ref定义的变量返回的是一个Ref对象 , 再scpipt里需要再调用 .value获取到它的值再操作 , 再模板里会自动解包 , 无需加 .value 但当且仅当在模板里执行命令的时候 , 如果它是深层数据 , 需要加上 .value

// 定义了info = { counter: 0 }
<h2 @click="info.counter.value++">{{ info.counter }}</h2>
  • 通过模板使用Ref来引用组件
<Book ref="BookListEl" />
// setup中
const bookListEl = ref() // 这里的就是Book标签的引用,如果是元素,那就是元素,如果是子组件,那就是子组件的引用
// 其实就是将ref绑定给了一个在setup里面定义的变量

shallowRef#

浅层监听

toRef / toRefs 函数#

将rective数据改为ref数据

unref 函数#

判断数据类型并解包ref数据

isRef 函数#

判断啊是否是Ref数据

triggerRef 函数#

shallowRef数据的深层数据变更不会在页面上刷新 , 使用该函数 , 传入shallowRef数据可以强制其内部数据在页面上刷新

readonly 函数#

  • 将传入的数据变成深度不可读数据 , 但返回的也是响应式的数据的代理 , 原数据可以被更改 .

computed 函数(引入)#

计算属性 , 把函数包装进computed函数 , 其返回的其实也是一个ref , 其内部也有一个 value属性

const fullName = computed(() => {
逻辑
return 数据
})
const fullName = computed({
get: function(){ 逻辑体 },
set: function(value){ 逻辑体 }
})

生命周期函数#

optionsAPIComposition Api
beforecreate-
created-
beforeMountonBeforeMount
mountedonMounted
beforeupdateonBeforeupdate
updatedonUpdated
beforeunmountonBeforeUnmount
unmountedonunmounted
activatedonActivated
deactivatedonDeactivated

provide inject#

  • provide(key, value) : 给子组件提供数据
  • inject(key[, 默认值]) : 子组件内接收提供的数据

watch 监听函数#

  • waich(监听源数据, (oldValue, newvalue)=> { 执行逻辑 }[, { 配置信息 }]) 配置信息可取值 deep: true // 深度监听 immediate: true // 第一次(初始化时)是否执行`

watchEffect 监听函数#

与 watch的区别是 watchEffect会自动收集其内部的变量 , 不需要指定监听数据源 , 且会在初始化时自动执行一次 watchEffect会返回一个函数 , 调用它会关闭此监听

defineProps#

[[#props 父传子]]

defineEmits#

[[#emit 子传父]]

defineExpose#

[[#defineExpose 按照组件进行调用]]

vue3 中的组件通讯#

props 父传子#

Parent.vue
<template>
<Child :msg="hMassage" />
</template>
<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
const hMassage = ref('hello')
</script>
<!-- Child.vue -->
<script setup>
const props = defineProps({ // 可以定义组件的属性 , 接收的对象名是可变的,不影响模板中的变量名
msg: String // 模板中的变量名只与这个有关
})
</script>
<template>{{ msg }}</template>

emit 子传父#

Child.vue
<script setup>
const emit = defineEmits(['myOut']) // 这里是暴露给父组件的函数名称,且emit只是形参,可以改变
</script>
<template>
<!--这里的emit就是上面定义的形参,第一个参数是函数名称,第二个是该函数传入的参数-->
<button @click="emit('myOut', 123)">+1</button>
</template>
<!-- Parent.vue -->
<template>
<!--绑定的是子组件暴露的emit内部的函数,为其传入回调函数,可达到在子组件内操作运行父组件内的函数-->
<Child @myOut="val => console.log(val)" />
</template>

v-model 父传子+子传父结合 = 父子互传#

在[[#v-model]]中有一部分讲解

Parent.vue
<template>
  <div>
    <my-input v-model:inText="text"/><!--这里model:后的字符串是给传递值起的别名,不写默认为modelValue -->
    <my-input :inText="text" @update:inText='new => inText = new'/><!--上下这两句实现的效果一样的 -->
    <h2>我是父组件里的输入文本 : {{ text }}</h2>
  </div>
</template>
<!-- Child.vue -->
<template>
  <input type="text" :value="inText" @input="onInput"><!-- 下面的事件处理和这行一样 -->
  <input type="text" :value="inText" @input="$emit('update:inText',$event.target.value)">
</template>
<!-- 无论是在template还是script里,inText取决于父组件起的别名,如果父组件没有起别名,那么默认值就是modelValue -->
<script setup>
const props = defineProps({
  inText: String // 这里是对象,在v-model有多个的时候,可以写多个值
})
console.log(props.inText)
const emits = defineEmits(['update:inText']) // 这里数组可以写很多值,用于传递多个v-model
function onInput(e) { // 用下面那个方法绑定值的时候可以不用写该函数
  emits('update:inText', e.target.value)
}
</script>

defineExpose 按照组件进行调用#

Parent.vue
<template>
<Child ref="childRef" />
<button @click="childRef?.open()">call child</button>
</template>
<script setup>
import { ref } from 'vue'
const childRef = ref()
</script>
<!-- Child.vue -->
<script setup>
function open() { alert('child method') }
defineExpose({ open }) // defineExpose会将组件内属性暴露出去
</script>

router 路由#

需要安装vue-router插件 创建一个路由

配置路由#

import { createRouter, createWebHistory } from 'vue-router'
import Utils from '@/utils/utils'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), // 这里的import引入基础目录前缀
// history: createWebHashHistory(), 采用哈希模式来控制路由
// history: createMemoryHistory(), 采用Memory模式来控制路由
routes: [
{
path: '/',
redirect: '/layout'
},
{
path: '/:pathMatch(.*)*', // 带最后一个星会使得匹配的路径被解析成数组
name: '404',
meta: {
title: '404'
},
component: () => import('../views/not-found/NotFound.vue')
},
{
path:'/User/:id',
name;'',
component: () => import('')
},
{
path: '/layout',
redirect: '/home',
name: '布局组件',
component: () => import('../layout/Layout.vue'),
children: [
{
path: '/home',
name: 'home',
meta: {
title: '首页'
},
component: () => import('../views/home/Home.vue')
},
{
path: '/iconConfig',
name: 'icon',
meta: {
module: '功能icon管理',
title: '功能列表'
},
component: () => import('../views/icon-config/IconConfig.vue')
}
]
}
]
})
// 动态引入路由
const isAdmin = true
if (isAdmin) {
router.addRoute({
path:'/User/:id',
name;'',
component: () => import('')
})
router.addRoute("name",{ // 这里会去寻找已有的路由进行替换
path: 'vip'
component: () => import('')
})
}
export default router

挂载路由#

怎么用?

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app
.use(router)
.mount('#app')

获取路由参数#

关于路由的参数获取方式

ip:端口/user/1233 匹配:/User/:id
<template>
<div class="user">
<!--·在模板中获取到id-->
<h2>User: {{ $route.params.id }}</h2>
<h2>未找到路径: {{ $route.params.pathMatch }}</h2>
<h2>query: {{ $route.query }}</h2>
<route-link to="/user/23423">用户23423</route-link>
</div>
</template>
<script>
created() {
// 获取匹配的id
console.log(this.$route.params.id)
// 匹配未找到的路由
console.log(this.$route.params.pathMatch)
}
</script>
<script setup>
import { useRoute } from 'vue-router'
// 获取route跳转id
const route = useRoute()
console.log(route.params.id)
console.log(route.query)
import { onBeforeRouteUpdate } from 'vue-router
// 同route跳转id
onBeforeRouteUpdate((to,from) =>{
console.log("from:", from.params.id)
console.log("to:", to.params.id)
}
// 未找到逻辑跳转
</script>

路由跳转#

import { userRoute } from 'vue-router'
const route = useRoute()
route.push("/about") // 进入/about路由界面
route.push({
path: '/about',
query: {
name: "s1dfas",
age: 131
}
}) // 进入/about路由界面
route.replace('/user/1233') // 进入/user/1233界面,把此页面替换
route.back() // 返回上一级
route.forward() // 向前一步
route.go(-1) // 传入数值,前进几步

路由导航守卫#

  1. 在router/index.js文件里面
router.beforeEach((to, from, next) => { // 进入页面之前
next(vm => {
console.log('组件实例:', vm)
})
return false // 取消跳转
return '/login' // 跳转到页面
return { // 传参跳转
path: '/about',
query: {
name: "s1dfas",
age: 131
}
}
// return的效果等同于next(参数)
next('/login')
})
router.beforeResolve() // 页面文件异步加载成功
router.afterEach() // 路由跳转完成
  1. 也可以写在页面的路由配置里面
const routes = [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
if (!isAdmin()) {
next('/403')
} else {
next()
}
}
}
]
  1. 也可以写在组件页面里面使用
<script>
export default {
beforeRouteEnter(to, from, next) {
// 组件实例还未被创建,不能访问 this
next(vm => {
console.log('组件实例:', vm)
})
},
beforeRouteUpdate() {
// 导航被复用,当数据更新,比如从一个帖子跳转到另一个帖子
},
beforeRouteLeave(to, from, next) {
const answer = window.confirm('还有未保存的内容,确定离开吗?')
if (answer) next()
else next(false)
}
}
</script>

 守卫执行顺序(完整跳转流程)#

  1. 导航触发
  2. 调用 beforeRouteLeave(组件内)
  3. 调用 beforeEach(全局)
  4. 调用 beforeRouteUpdate(组件内,若复用)
  5. 调用 beforeEnter(路由独享)
  6. 解析异步路由组件
  7. 调用 beforeRouteEnter(组件内)
  8. 调用 beforeResolve(全局)
  9. 导航确认
  10. 调用 afterEach(全局)

状态管理#

Vuex#

State#

getters#

mutations#

actions#

pinia#

安装#

npm install pinia
// or
yarn add pinia

挂载使用#

main.ts
import { createPinia } from 'pinia'
app
.use(createPinia())
.mount('#app')

定义store#

import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
counter: 0,
friends: [
{ id: 1, name: 'John' },
{ id: 2, name: 'Jane' }
]
}),
getters: {
double: state => state.counter * 2,
doubleAdd: state => state.double * 2 + 1,
getFriendById: state => id => state.friends.find(friend => friend.id === id),
},
actions: {
add() {
this.counter++
return "这是add函数返回值"
},
subtract() {
this.counter--
return "这是subtract函数返回值"
}
},
});

使用store#

<template>
<div >
<h2>我是HeaderInStore {{ counterStore.counter }} </h2>
<h2>我是结构出来的counter {{ counter }} </h2>
<h2>我是双倍 {{ counterStore.double }} </h2>
<h2>我是双倍加一 {{ counterStore.doubleAdd }} </h2>
<h2>朋友1 {{ counterStore.getFriendById(1) }} </h2>
<h2>朋友2 {{ counterStore.getFriendById(2) }} </h2>
<button @click="add">+1</button>
<button @click="counterStore.add">+1</button>
<button @click="subtract">-1</button>
<button @click="counterStore.subtract">-1</button>
<button @click="patchCounter">批量修改Store</button>
<button @click="reSet">重置Store</button>
</div>
</template>
<script setup>
import { storeToRefs } from 'pinia';
import { useCounterStore } from '@/stores/counter.js';
const counterStore = useCounterStore()
// 参数解构需要用ref包裹
const { counter } = storeToRefs(counterStore)
// 方法解构不需要用ref包裹
const { add, subtract} = counterStore
function patchCounter() {
counterStore.$patch({ // 批量修改
counter: 100,
friends: [
{ id: 1, name: '张三', age: 18 },
{ id: 2, name: '李四', age: 19 }
]
})
}
// 订阅状态变化
counterStore.$subscribe((mutation, state) => {
console.log('mutation:', mutation) // 这次“怎么变的”
/* { type: "direct"直接修改 / "patch function"重置 / "patch object"派发patch批量修改,
storeId: "counter",
events: 此次发生变化的改变情况,
payload: 只有在patch操作才有,指的是修改成的内容
} */
console.log('state :', state) // 变化后的完整 state
})
// 订阅动作
counterStore.$onAction(({ name, store, args, after, onError }) => {
console.log('action 名:', name) // 被调的方法名
console.log('参数列表:', args) // 调用时传的实参,默认传递点击事件event对象
console.log('当前 store:', store) // 当前 store 实例
console.log('是同一个 store:', store === counterStore) // 就是同一个 store 实例
after((result) => {
console.log('成功回调, 返回值:', result)
})
onError((err) => {
console.log('失败回调, 错误对象:', err)
})
})
function reSet() {
counterStore.$reset() // 重置状态
}
</script>

网络请求 — axios#

安装#

npm install axios

简单使用#

import axios from 'axios'
axios.get('http://localhost:3000/api/users').then(res => {
console.log(res.data)
})
axios.defaults.baseURL = 'http://localhost:3000'
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.timeout = 10000;
axios.get('/api/users',{
params: {
name: '张三',
age: 18
}
}).then(res => {
console.log(res.data)
})
axios.post('/api/users', {
name: '张三',
age: 18
}).then(res => {
console.log(res.data)
})

实例创建#

const instance = axios.create({
baseURL: 'http://localhost:3000',
timeout: 10000,
headers: { 'X-Custom-Header': 'foobar' }
params: {}
})
instance.get('/api/users',{
params: {
name: '张三',
age: 18
}
})
instance.post('/api/users', {})
instance.interceptors.request.use( )

封装#

import axios from 'axios'
const request = axios.create({
baseURL: "192.168.2.1:2000", // 基础URL
timeout: 10000, // 请求超时时间
headers: { 'Content-Type': 'application/json'} // 默认请求头
})
// 添加请求拦截器
request.interceptors.request.use((config) => {
// 在这里可以添加请求拦截器
console.log('请求拦截器:', config)
return config
})
// 添加响应拦截器
request.interceptors.response.use((response) => {
// 在这里可以处理响应数据
console.log('响应拦截器:', response)
return response.data
})
export default request
分享

如果这篇文章对你有帮助,欢迎分享给更多人!

Vue.js 入门指南
https://www.403bug.top/posts/vue-guide/
作者
ma
发布于
2025-08-15
许可协议
CC BY-NC-SA 4.0

部分信息可能已经过时

目录