一.router-link
①不带参数
<router-link :to="{name:'guest'}">跳转到路由为guest页面</router-link>
<router-link :to="{path:'guest'}">跳转到路由为guest页面</router-link>
router-link
中链接如果是**’ / '**开始就是从根路由开始,如果开始不带 ’ / ',则从当前路由开始.举个栗子: 当前页面所在路由为 /home/goods 设置
router-link
链接…
{path:'guest'}
跳转后页面所在路由为 /home/guest…
{path:'/guest'}
跳转后页面所在路由为 /guest
②带参数
1️⃣query
传参数
<router-link :to="{path:'guest',query:{id:1}}">跳转到路由为guest页面</router-link>
<router-link :to="{name:'guest',query:{id:1}}">跳转到路由为guest页面</router-link>
不需要路由配置
2️⃣接收参数
<script setup lang="ts">
import { useRoute } from 'vue-router';
import { onMounted } from 'vue';
const route = useRoute();
onMounted(() => {
console.log(route.query.id); //1
})
</script>
1️⃣params
传参数
<router-link :to="{name:'guest',params:{id:1}}">跳转到路由为guest页面</router-link>
路由配置
path:"/home/:id"
或者path:"/home.id"
路由不配置
path
中的参数id
第一次可请求,刷新页面id
会消失路由配置
path
中的参数id
刷新页面id
会保留
2️⃣接收参数
<script setup lang="ts">
import { useRoute } from 'vue-router';
import { onMounted } from 'vue';
const route = useRoute();
onMounted(() => {
console.log(route.params.id); //1
})
</script>
二.router.push()
代码环境
<template>
<button @click="clickGo">跳转到路由为guest页面</button>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router';
const router = useRouter();
const clickGo = () => {
router.push('guest'); //调用router.push()
}
</script>
①不带参数
router.push('guest');
router.push({name:'guest'});
router.push(path:{'guest'});
②带参数
1️⃣query
传参数
router.push({ name: 'guest', query: { id: 1 } });
router.push({ path: 'guest', query: { id: 1 } });
2️⃣接收参数
<script setup lang="ts">
import { useRoute } from 'vue-router';
import { onMounted } from 'vue';
const route = useRoute();
onMounted(() => {
console.log(route.query.id); //1
})
</script>
1️⃣params
传参数
router.push({ name: 'guest', params: { id: 1 } });
2️⃣接收参数
<script setup lang="ts">
import { useRoute } from 'vue-router';
import { onMounted } from 'vue';
const route = useRoute();
onMounted(() => {
console.log(route.params.id); //1
})
</script>
三.路由props传递
我们可以将下面的代码
//路由
const routes = [{ path: '/user/:id', ***ponent: User }]
//组件使用
const User = {
template: '<div>User {{ $route.params.id }}</div>'
}
替换成
javascript">//路由
const routes = [{ path: '/user/:id', ***ponent: User, props: true }]
//组件使用
const User = {
// 请确保添加一个与路由参数完全相同的 prop 名
props: ['id'],
template: '<div>User {{ id }}</div>'
}
~~个人笔记,不足之处请指出··