Vue 3 快速上手学习笔记

编程 · 07-29 · 195 人浏览

Vue 3简介

Vue 3中文官网:https://cn.vuejs.org/

官方发版地址:https://github.com/vuejs/core/releases

截止2024年7月17日,最新的公开版本为:v3.4.32

创建Vue 3工程

前提条件:

  • 已安装 18.3 或更高版本的Node.js
  • 安装好pnpm:npm i -g pnpm

Vite是新一代前端构建工具,官方推荐基于Vite创建项目,具体操作如下。

创建项目命令:pnpm create vue@latest,将会安装并执行 create-vue,它是 Vue 官方的项目脚手架工具。

具体配置:

√ 请输入项目名称: ... vue-project
√ 是否使用 TypeScript 语法? ... 是
√ 是否启用 JSX 支持? ... 否
√ 是否引入 Vue Router 进行单页面应用开发? ... 否
√ 是否引入 Pinia 用于状态管理? ... 否
√ 是否引入 Vitest 用于单元测试? ... 否
√ 是否要引入一款端到端(End to End)测试工具? » 不需要
√ 是否引入 ESLint 用于代码质量检测? ... 否
√ 是否引入 Vue DevTools 7 扩展用于调试? (试验阶段) ... 否

项目创建后,通过以下步骤安装依赖并启动开发服务器:

cd vue-project
pnpm i
pnpm run dev

安装官方推荐的VS Code插件:Vue - Official。

Vue 3核心语法

选项式 API 和组合式 API

  • Vue 2的API设计是Options(选项)风格的,不便维护和复用
  • Vue 3的API设计是Composition(组合)风格的,用函数的方式,更加优雅的组织代码,让相关功能代码更加有序的组织在一起

setup

setup是Vue 3中的一个新配置项,值是一个函数。它是 Composition API 表演的舞台,组件中所用到的:数据、方法、计算属性、监视等等,均配置在setup中。

特点如下:

  • setup 函数若返回一个对象,则对象中的内容可直接在模板中使用;若返回一个函数,则可以自定义渲染内容
  • setup 中访问thisundefined
  • setup 函数在beforeCreate之前调用,“领先”于所有钩子执行

setup 与 Options API 关系

  • Vue 2的配置(datamethods...)中可以访问到 setup 中的属性、方法
  • 但 setup 中不能访问到Vue 2的配置
  • 如果与Vue 2冲突,则 setup 优先

setup 语法糖

setup函数有一个语法糖,可以把setup独立出去。

首先,删除src文件夹下的所有文件,然后在src文件夹下新建文件main.ts:

import { createApp } from 'vue'
import App from './App.vue'

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

接着,在src文件夹下新建文件App.vue:

<template>
  <Person />
</template>

<script lang="ts">
import Person from './components/Person.vue'
export default {
  name: 'App', // 组件名
  components: {
    Person, // 注册子组件
  },
}
</script>

最后,新建文件src\components\Person.vue:

<template>
  <div class="person">
    <h2>姓名:{{ name }}</h2>
    <h2>年龄:{{ age }}</h2>
    <button @click="changName">修改名字</button>
    <button @click="changAge">年龄+1</button>
    <button @click="showTel">点我查看联系方式</button>
  </div>
</template>

<!-- setup语法糖 -->
<script setup lang="ts" name="Person">
console.log(this) // undefined

// 数据(注意:此时的name、age、tel都不是响应式数据)
let name = '张三'
let age = 18
let tel = '13888888888'

// 方法
function changName() {
  name = '李四' // 注意:此时这么修改name页面是不变化的
}
function changAge() {
  console.log(age)
  age += 1
}
function showTel() {
  alert(tel)
}
</script>

<style scoped>
.person {
  background-color: skyblue;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}

button {
  margin: 0 5px;
}
</style>

扩展:上述代码的name="Person",需要安装一个插件:
第一步:pnpm i vite-plugin-vue-setup-extend -D

第二步:修改文件vite.config.ts:

import VueSetupExtend from 'vite-plugin-vue-setup-extend'

export default defineConfig({
  plugins: [vue(), VueSetupExtend()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
})

第三步:<script setup lang="ts" name="Person">

ref 与 reactive

宏观角度看:

  • ref用来定义:基本类型数据、对象类型数据(内部其实是调用reactive函数)
  • reactive用来定义:对象类型数据(响应式数据是“深层次”的)
<template>
  <div class="person">
    <h2>姓名:{{ name }}</h2>
    <h2>汽车:一台{{ car.brand }},价值{{ car.price }}万</h2>
    <h2>游戏:</h2>
    <ul>
      <li v-for="g in games" :key="g.id">{{ g.name }}</li>
    </ul>
    <button @click="changeName">修改名字</button>
    <button @click="changeCarPrice">修改汽车价格</button>
    <button @click="changeFirstGame">修改第一个游戏</button>
  </div>
</template>

<script setup lang="ts" name="Person">
import { ref, reactive } from 'vue'

// ref对象,其value属性是响应式的
let name = ref('张三')
let car = ref({ brand: '奔驰', price: 100 })
let games = reactive([
  { id: 'ahsgdyfa01', name: '英雄联盟' },
  { id: 'ahsgdyfa02', name: '王者荣耀' },
  { id: 'ahsgdyfa03', name: '原神' },
])

function changeName() {
  // JS中操作ref对象时需.value
  name.value = '李四'
}

function changeCarPrice() {
  car.value.price += 100
}

function changeFirstGame() {
  games[0].name = '流星蝴蝶剑'
}
</script>

两者区别:

  • ref创建的变量必须使用.value(可以使用Vue插件自动添加.value)
  • reactive重新分配一个新对象,会失去响应式(可以使用Object.assign去整体替换)
<template>
  <div class="person">
    <h2>汽车:一台{{ car.brand }},价值{{ car.price }}万</h2>
    <button @click="changeCar">修改汽车</button>
  </div>
</template>

<script setup lang="ts" name="Person">
import { reactive } from 'vue'
let car = reactive({ brand: '奔驰', price: 100 })

function changeCar() {
  Object.assign(car, { brand: '宝马', price: 200 })
}
</script>

使用原则:

  • 若需要一个基本类型的响应式数据,必须使用ref
  • 若需要一个响应式对象,层级不深,ref、reactive都可以
  • 若需要一个响应式对象,层级较深,推荐使用reactive

toRefs 与 toRef

  • toRef:将一个响应式对象中的每个属性,转换为ref对象
  • toRefs与toRef功能一致,但toRefs可批量转换
<template>
  <div class="person">
    <h2>姓名:{{ person.name }}</h2>
    <h2>年龄:{{ person.age }}</h2>
    <h2>性别:{{ person.gender }}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">修改年龄</button>
    <button @click="changeGender">修改性别</button>
  </div>
</template>

<script lang="ts" setup name="Person">
import { reactive, toRefs, toRef } from 'vue'

// 数据
let person = reactive({ name: '张三', age: 18, gender: '男' })
let { name, age } = toRefs(person)
let gender = toRef(person, 'gender')

// 方法
function changeName() {
  name.value += '~'
}

function changeAge() {
  age.value += 1
}

function changeGender() {
  gender.value = '女'
}
</script>

computed

<template>
  <div class="person">
    姓:<input type="text" v-model="firstName" /> <br />
    名:<input type="text" v-model="lastName" /> <br />
    全名:<span>{{ fullName }}</span> <br />
    <button @click="changeFullName">全名改为:li-si</button>
  </div>
</template>

<script setup lang="ts" name="App">
import { ref, computed } from 'vue'

let firstName = ref('zhang')
let lastName = ref('san')

// 计算属性:只读取,不修改
// let fullName = computed(() => {
//   return firstName.value + '-' + lastName.value
// })

// 计算属性:既读取又修改
let fullName = computed({
  // 读取
  get() {
    return firstName.value + '-' + lastName.value
  },
  // 修改
  set(val) {
    firstName.value = val.split('-')[0]
    lastName.value = val.split('-')[1]
  },
})

function changeFullName() {
  fullName.value = 'li-si'
}
</script>

watch

情况一:监视【ref】定义的【基本类型】数据。

<template>
  <div class="person">
    <h2>当前求和为:{{ sum }}</h2>
    <button @click="changeSum">点我+1</button>
  </div>
</template>

<script lang="ts" setup name="Person">
import { ref, watch } from 'vue'

let sum = ref(0)

function changeSum() {
  sum.value += 1
}

const stopWatch = watch(sum, (newValue, oldValue) => {
  console.log('sum变化了', newValue, oldValue)
  if (newValue >= 5) {
    stopWatch()
  }
})
</script>

情况二:监视【ref】定义的【对象类型】数据。

<template>
  <div class="person">
    <h2>姓名:{{ person.name }}</h2>
    <h2>年龄:{{ person.age }}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">修改年龄</button>
    <button @click="changePerson">修改整个人</button>
  </div>
</template>

<script lang="ts" setup name="Person">
import { ref, watch } from 'vue'

let person = ref({
  name: '张三',
  age: 18,
})

function changeName() {
  person.value.name += '~'
}

function changeAge() {
  person.value.age += 1
}

function changePerson() {
  person.value = { name: '李四', age: 90 }
}

// 监视对象地址值,若想监视对象内部属性变化,需手动开启深度监视
watch(
  person,
  (newValue, oldValue) => {
    console.log('person变化了', newValue, oldValue)
  },
  { deep: true }
)
</script>

情况三:监视【reactive】定义的【对象类型】数据。

<template>
  <div class="person">
    <h2>姓名:{{ person.name }}</h2>
    <h2>年龄:{{ person.age }}</h2>
    <button @click="changeName">修改名字</button>
    <button @click="changeAge">修改年龄</button>
    <button @click="changePerson">修改整个人</button>
  </div>
</template>

<script lang="ts" setup name="Person">
import { reactive, watch } from 'vue'

let person = reactive({
  name: '张三',
  age: 18,
})

function changeName() {
  person.name += '~'
}

function changeAge() {
  person.age += 1
}

function changePerson() {
  Object.assign(person, { name: '李四', age: 80 })
}

// 默认开启深度监视
watch(person, (newValue, oldValue) => {
  console.log('person变化了', newValue, oldValue)
})
</script>

情况四:监视【ref】或【reactive】定义的【对象类型】数据中的某个属性。

<template>
  <div class="person">
    <h2>姓名:{{ person.name }}</h2>
    <h2>汽车:{{ person.car.c1 }}、{{ person.car.c2 }}</h2>
    <button @click="changeName">修改姓名</button>
    <button @click="changeC1">修改第一台车</button>
    <button @click="changeC2">修改第二台车</button>
    <button @click="changeCar">修改整台车</button>
  </div>
</template>

<script lang="ts" setup name="Person">
import { reactive, watch } from 'vue'

let person = reactive({
  name: '张三',
  car: {
    c1: '奔驰',
    c2: '宝马',
  },
})

function changeName() {
  person.name += '~'
}
function changeC1() {
  person.car.c1 = '奥迪'
}
function changeC2() {
  person.car.c2 = '大众'
}
function changeCar() {
  person.car = { c1: '雅迪', c2: '爱玛' }
}

// 监视响应式对象中的某个属性,且该属性是基本类型的,要写成函数
// watch(
//   () => person.name,
//   (newValue, oldValue) => {
//     console.log('person.name变化了', newValue, oldValue)
//   }
// )

// 监视响应式对象中的某个属性,且该属性是对象类型的,可直接写也可写成函数,建议写成函数
watch(
  () => person.car,
  (newValue, oldValue) => {
    console.log('person.car变化了', newValue, oldValue)
  },
  { deep: true } // 要关注对象内部,需手动开启深度监视
)
</script>

情况五:监视上述的多个数据。

watch(
  [() => person.name, person.car],
  (newValue, oldValue) => {
    console.log('person.car变化了', newValue, oldValue)
  },
  { deep: true }
)

watchEffect

watch对比watchEffect:

  1. 都能监听响应式数据的变化,不同的是监听数据变化的方式不同
  2. watch:要明确指出监视的数据
  3. watchEffect:不用明确指出监视的数据(函数中用到哪些属性,就监视哪些属性)
<template>
  <div class="person">
    <h1>需求:水温达到50℃,或水位达到30cm,则联系服务器</h1>
    <h2>水温:{{ temp }}</h2>
    <h2>水位:{{ height }}</h2>
    <button @click="changeTemp">水温+10</button>
    <button @click="changeheight">水位+10</button>
  </div>
</template>

<script lang="ts" setup name="Person">
import { ref, watch, watchEffect } from 'vue'

let temp = ref(0)
let height = ref(0)

function changeTemp() {
  temp.value += 10
}

function changeheight() {
  height.value += 10
}

// watch需要明确指出要监视:temp、height
// watch([temp, height], (value) => {
//   const [newTemp, newHeight] = value
//   if (newTemp >= 50 || newHeight >= 30) {
//     console.log('联系服务器')
//   }
// })

// watchEffect不用明确指出监视的数据
const stopWtach = watchEffect(() => {
  if (temp.value >= 50 || height.value >= 30) {
    console.log('联系服务器')
  }
  // 水温达到100,或水位达到50,取消监视
  if (temp.value === 100 || height.value === 50) {
    console.log('清理了,取消监视')
    stopWtach()
  }
})
</script>

标签 ref 属性

用在普通DOM标签上:

<template>
  <div class="person">
    <h2 ref="title2">前端</h2>
    <button @click="showLog">点我打印内容</button>
  </div>
</template>

<script lang="ts" setup name="Person">
import { ref } from 'vue'

let title2 = ref()

function showLog() {
  // 通过ref获取元素
  console.log(title2.value)
}
</script>

用在组件标签上,子组件Person.vue:

<template>
  <div class="person">
    <h2 ref="title2">前端</h2>
  </div>
</template>

<script lang="ts" setup name="Person">
import { ref, defineExpose } from 'vue'

let name = ref('张三')
let age = ref(18)

// 使用defineExpose将组件中的数据交给外部
defineExpose({ name, age })
</script>

父组件App.vue:

<template>
  <h1>Hello Vue</h1>
  <button @click="test">测试一下</button>
  <Person ref="ren" />
</template>

<script lang="ts" setup name="App">
import Person from './components/Person.vue'
import { ref } from 'vue'

let ren = ref()

function test() {
  console.log(ren.value.name)
  console.log(ren.value.age)
}
</script>

<style scoped>
button {
  margin: 0 0 30px;
}
</style>

TS语法

新建文件src\types\index.ts:

// 定义接口
export interface PersonInter {
  id: string
  name: string
  age?: number // age 可有可无
}

// 自定义类型
// export type Persons = Array<PersonInter> // 另一种写法
export type Persons = PersonInter[]

父组件App.vue:

<template>
  <Person />
</template>

<script lang="ts" setup name="App">
import Person from '@/components/Person.vue'
</script>

子组件Person.vue:

<template>
  <div class="person">
    <h2 ref="title2">前端</h2>
  </div>
</template>

<script lang="ts" setup name="Person">
import { type PersonInter, type Persons } from '@/types'

let person: PersonInter = { id: '1', name: '张三', age: 25 }
let persons: Persons = [person, { id: '2', name: '李四', age: 30 }, { id: '3', name: '王五', age: 28 }]
</script>

Props

父组件App.vue:

<template>
  <Person :list="persons" />
</template>

<script lang="ts" setup name="App">
import Person from '@/components/Person.vue'
import { reactive } from 'vue'
import { type Persons } from './types'

let persons = reactive<Persons>([
  { id: 'e98219e12', name: '张三', age: 18 },
  { id: 'e98219e13', name: '李四' },
  { id: 'e98219e14', name: '王五', age: 20 },
])
</script>

子组件Person.vue:

<template>
  <div class="person">
    <ul>
      <li v-for="p in list" :key="p.id">{{ p.name }}-{{ p.age }}</li>
    </ul>
  </div>
</template>

<script lang="ts" setup name="Person">
import { defineProps } from 'vue'
import { type Persons } from '@/types'

// 第一种写法:仅接收
// defineProps(['list'])

// 第二种写法:接收 + 限制类型
// defineProps<{ list: Persons }>()

// 第三种写法:接收 + 限制类型 + 限制必要性 + 指定默认值
withDefaults(defineProps<{ list?: Persons }>(), {
  list: () => [{ id: '2', name: '小猪佩奇', age: 18 }],
})
</script>

生命周期

Vue组件实例在创建时要经历一系列的初始化步骤,在此过程中Vue会在合适的时机,调用特定的函数,从而让开发者有机会在特定阶段运行自己的代码,这些特定的函数统称为:生命周期钩子。

生命周期整体分为四个阶段,分别是:创建、挂载、更新、卸载,每个阶段都有两个钩子,一前一后。Vue 3生命周期:

  • 创建阶段:setup
  • 挂载阶段:onBeforeMountonMounted
  • 更新阶段:onBeforeUpdateonUpdated
  • 卸载阶段:onBeforeUnmountonUnmounted

常用钩子:onMounted(挂载完毕)、onUpdated(更新完毕)、onBeforeUnmount(卸载之前)。

自定义hook

hook本质上是一个函数,把setup函数中使用的Composition API进行了封装。自定义hook的优势:复用代码, 让setup中的逻辑更清楚易懂。

父组件App.vue:

<template>
  <Person />
</template>

<script lang="ts" setup name="App">
import Person from '@/components/Person.vue'
</script>

子组件Person.vue:

<template>
  <img v-for="(dog, index) in dogList" :key="index" :src="dog" />
  <br />
  <button @click="getDog">再来一只狗</button>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'App',
})
</script>

<script setup lang="ts">
import useDog from '@/hooks/useDog'

let { dogList, getDog } = useDog()
</script>

<style scoped>
.person {
  background-color: skyblue;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}
li {
  font-size: 20px;
}
img {
  height: 100px;
  margin-right: 10px;
}
</style>

新建文件src\hooks\useDog.ts:

import { reactive, onMounted } from 'vue'
import axios, { AxiosError } from 'axios'
// pnpm i axios

export default function () {
  let dogList = reactive<string[]>([])

  // 方法
  async function getDog() {
    try {
      // 发请求
      let { data } = await axios.get('https://dog.ceo/api/breed/pembroke/images/random')
      // 维护数据
      dogList.push(data.message)
    } catch (error) {
      // 处理错误
      const err = <AxiosError>error
      console.log(err.message)
    }
  }

  // 挂载钩子
  onMounted(() => {
    getDog()
  })

  //向外部暴露数据
  return { dogList, getDog }
}

路由

两个注意点:

  • 路由组件通常存放在pages或views文件夹,一般组件通常存放在components文件夹
  • 通过点击导航,视觉效果上“消失” 了的路由组件,默认是被卸载掉的,需要的时候再去挂载

路由器工作模式

  • history模式

    • 优点:URL更加美观,不带有#
    • 缺点:后期项目上线,需要服务端配合处理路径问题,否则刷新会有404错误
  • hash模式

    • 优点:兼容性更好,因为不需要服务器端处理路径
    • 缺点:URL带有#不太美观,且在SEO优化方面相对较差

基本使用

首先,新建路由组件src\pages\About.vue:

<template>
  <div class="about">
    <h2>关于</h2>
  </div>
</template>

<script setup lang="ts" name="About"></script>

<style scoped>
.about {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: rgb(85, 84, 84);
  font-size: 18px;
}
</style>

src\pages\Home.vue:

<template>
  <div class="home">
    <img src="@/assets/logo.svg" width="200" />
  </div>
</template>

<script setup lang="ts" name="Home"></script>

<style scoped>
.home {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>

src\pages\News.vue:

<template>
  <div class="news">
    <!-- 导航区 -->
    <ul>
      <li v-for="news in newsList" :key="news.id">
        <!-- 带query参数,to字符串写法 -->
        <!-- <RouterLink :to="`/news/detail?id=${news.id}`">{{ news.title }}</RouterLink> -->
        <!-- 带query参数,to对象写法 -->
        <RouterLink :to="{ path: '/news/detail', query: { id: news.id } }">{{ news.title }}</RouterLink>
      </li>
    </ul>
    <!-- 展示区 -->

    <div class="news-content"><RouterView></RouterView></div>
  </div>
</template>

<script setup lang="ts" name="News">
import { reactive } from 'vue'
import { RouterView } from 'vue-router'

const newsList = reactive([
  { id: '001', title: '新闻001', content: '这是新闻001的内容' },
  { id: '002', title: '新闻002', content: '这是新闻002的内容' },
  { id: '003', title: '新闻003', content: '这是新闻003的内容' },
])
</script>

<style scoped>
.news {
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  height: 100%;
}

.news ul {
  margin-top: 30px;
  /* list-style: none; */
  padding-left: 10px;
}
.news li::marker {
  color: #64967e;
}
.news li > a {
  font-size: 18px;
  line-height: 40px;
  text-decoration: none;
  color: #64967e;
  text-shadow: 0 0 1px rgb(0, 84, 0);
}
.news-content {
  width: 70%;
  height: 90%;
  border: 1px solid;
  margin-top: 20px;
  border-radius: 10px;
}
</style>

src\pages\Detail.vue:

<template>
  <ul class="news-list">
    <li>编号:{{ query.id }}</li>
    <li>标题:xxx</li>
    <li>内容:xxx</li>
  </ul>
</template>

<script setup lang="ts" name="">
import { toRefs } from 'vue'
import { useRoute } from 'vue-router'
let route = useRoute()
let { query } = toRefs(route)
</script>

<style scoped>
.news-list {
  list-style: none;
  padding-left: 20px;
}

.news-list > li {
  line-height: 30px;
}
</style>

然后,新建路由配置文件src\router\index.ts:

import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/pages/Home.vue'
import News from '@/pages/News.vue'
import About from '@/pages/About.vue'
import Detail from '@/pages/Detail.vue'

// 创建路由器
const router = createRouter({
  history: createWebHistory(), // history模式,hash模式为createWebHashHistory
  routes: [
    {
      name: 'home', // 给路由规则命名,以简化路由跳转及传参
      path: '/home',
      component: Home,
    },
    {
      path: '/news',
      component: News,
      children: [ // 嵌套路由
        {
          path: 'detail', // 子级路由不用写 /
          component: Detail,
        },
      ],
    },
    {
      path: '/about',
      component: About,
    },
    {
      path: '/',
      redirect: '/home', // 重定向
    },
  ],
})
export default router

main.ts:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'

const app = createApp(App)
app.use(router)
app.mount('#app')

App.vue:

<template>
  <div class="app">
    <h2 class="title">Vue路由测试</h2>
    <!-- 导航区 -->
    <div class="navigate">
      <RouterLink to="/home" active-class="active">首页</RouterLink>
      <RouterLink to="/news" active-class="active">新闻</RouterLink>
      <!-- to对象写法,上面是to字符串写法 -->
      <RouterLink :to="{ path: '/about' }" active-class="active">关于</RouterLink>
      <!-- 直接通过名字跳转 -->
      <RouterLink :to="{ name: 'home' }">跳转</RouterLink>
    </div>
    <!-- 展示区 -->
    <div class="main-content">
      <RouterView></RouterView>
    </div>
  </div>
</template>

<script lang="ts" setup name="App">
import { RouterLink, RouterView } from 'vue-router'
</script>

<style>
.title {
  text-align: center;
  word-spacing: 5px;
  margin: 30px 0;
  height: 70px;
  line-height: 70px;
  border-image: linear-gradient(45deg, gray, white);
  border-radius: 10px;
  box-shadow: 0 0 2px;
  font-size: 30px;
}
.navigate {
  display: flex;
  justify-content: space-around;
  margin: 0 100px;
}
.navigate a {
  display: block;
  text-align: center;
  width: 90px;
  height: 40px;
  line-height: 40px;
  border-radius: 10px;
  background-color: gray;
  text-decoration: none;
  color: white;
  font-size: 18px;
  letter-spacing: 5px;
}
.navigate a.active {
  background-color: #64967e;
  color: #ffc268;
  font-weight: 900;
  text-shadow: 0 0 1px black;
  font-family: 微软雅黑;
}
.main-content {
  margin: 0 auto;
  margin-top: 30px;
  border-radius: 10px;
  width: 90%;
  height: 400px;
  border: 1px solid;
}
</style>

路由传参

params参数:

  • 传递params参数时,若使用to对象写法,必须使用name配置项,不能用path
  • 传递params参数时,需提前在路由规则中占位

修改路由规则src\router\index.ts:

routes: [
    {
      path: '/news',
      component: News,
      children: [
        {
          name: 'detail',
          path: 'detail/:id/:content?', // ?表示可选参数
          component: Detail,
        },
      ],
    },
  ],

修改src\pages\News.vue:

<!-- 带params参数,to字符串写法 -->
<!-- <RouterLink :to="`/news/detail/${news.id}`">{{ news.title }}</RouterLink> -->
<!-- 带params参数,to对象写法 -->
<RouterLink :to="{ name: 'detail', params: { id: news.id } }">{{ news.title }}</RouterLink>

修改src\pages\Detail.vue:

<template>
  <ul class="news-list">
    <li>编号:{{ params.id }}</li>
    <li>标题:xxx</li>
    <li>内容:xxx</li>
  </ul>
</template>

<script setup lang="ts" name="">
import { toRefs } from 'vue'
import { useRoute } from 'vue-router'
let route = useRoute()
let { params } = toRefs(route)
</script>

路由规则props配置

作用:让路由组件更方便的收到参数(可将路由参数作为props传给组件)。

布尔值写法

修改路由规则src\router\index.ts:

children: [
  {
    name: 'detail',
    path: 'detail/:id/:content?',
    component: Detail,
    // 布尔值写法,把收到的每一组 params 参数,作为props传给Detail组件
    props: true,
  },
],

修改src\pages\Detail.vue:

<template>
  <ul class="news-list">
    <li>编号:{{ id }}</li>
    <li>标题:xxx</li>
    <li>内容:xxx</li>
  </ul>
</template>

<script setup lang="ts" name="">
defineProps(['id'])
</script>

函数写法

children: [
  {
    name: 'detail',
    path: 'detail/:id/:content?',
    component: Detail,
    // 函数写法,把返回对象中的每一组key-value作为props传给Detail组件
    props(route) {
      // return route.query
      return route.params
    },
  },
],

对象写法

children: [
  {
    name: 'detail',
    path: 'detail/:id/:content?',
    component: Detail,
    // 对象写法,把对象中的每一组key-value作为props传给Detail组件
    props: {
      id: '123',
      content: 'hello world',
    },
  },
],

replace属性

作用:控制路由跳转时操作浏览器历史记录的模式。

浏览器历史记录有两种写入方式:push和replace:

  • push 追加历史记录(默认值)
  • replace 替换当前记录

开启replace模式:

<RouterLink replace to="/news" active-class="active">新闻</RouterLink>

编程式导航

路由组件的两个重要属性:$route和$router变成了两个hooks,可脱离实现路由跳转。

修改src\pages\Home.vue,实现3s后跳转到新闻页面:

<script setup lang="ts" name="Home">
import { onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

onMounted(() => {
  setTimeout(() => {
    router.push('/news') // 类似to语法,也可使用 router.replace
  }, 3000)
})
</script>
JavaScript Vue
Theme Jasmine by Kent Liao