Vue-router

文章详细介绍了Vue-router的使用,包括基础路由配置,如何通过`router-link`和`router-view`实现页面跳转,以及路由参数的传递。此外,还讨论了多级路由的设置和在不同层级间传递参数的方法。最后,文章讲解了如何通过props将路由参数绑定到组件属性,以简化模板中的代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

路由(Vue-router)

1. 基础路由

vue-router: 插件库,用来实现

这里使用vue2, 因此需要安装3版本的vue-router插件

npm i vue-router@3

实现单页面路由跳转
在这里插入图片描述
定义结构:About.vue, Home.vue, 用来指定跳转的组件内容

<template>
    <div>我是About的内容</div>   // 类似的Home修改内容和下面组件名称即可
</template>

<script>

export default ({
    name: 'AboutPage'
})
</script>

在入口的App.vue中进行引入

<template>
  <div>
    <router-link class="item-group" active-class="active" to="/about">About</router-link>
    <router-link class="item-group" active-class="active" to="/home">Home</router-link>

    <router-view></router-view>
  </div>
</template>

<script>

export default {
  name: 'App',
  components: {
  }
}
</script>

router-link: vue-router中的特殊标签,本质上是一个 a标签,会处理生成router
router-view: 指定路由跳转后渲染内容的位置
to: 指定路由的路径

定义全局生效的路由配置文件:

// 全局router的引入
import VueRouter from 'vue-router'

// 引入组件
import About from '../components/About'
import Home from '../components/Home'

export default new VueRouter({
    routes: [
        {
            path: '/about',
            component: About
        },
        {
            path: '/home',
            component: Home
        }
    ]
})

在main.js中配置和引入vue-router

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

// 引入router的插件
import VueRouter from 'vue-router'

// 应用router
Vue.use(VueRouter)

import router from './router/index'

new Vue({
  render: h => h(App),
  router: router
}).$mount('#app')

配置结束


2. 路由参数

<div id="app">
        <h1>Hello App!</h1>
        <p>
            <router-link to="/user/1">我是User1</router-link>
            <router-link to="/user/2">我是User2</router-link>
        </p>
        <!-- 用来显示数据 -->
        <router-view></router-view>  
    </div>
<template id="user">
    <div>{{ $route.params }}</div>
</template>

<script>
    // 定义组件
    const User = { template: '#user' }

    routes = [
        { path: '/user/:id', component: User }
    ]

    const router = VueRouter.createRouter({
        // 4. Provide the history implementation to use. We are using the hash history for simplicity here.
        history: VueRouter.createWebHashHistory(),
        routes, // short for `routes: routes`
    })

    // 5. Create and mount the root instance.
    const app = Vue.createApp({})

    app.use(router)

    app.mount('#app')
</script>

问题:当使用参数的时候,使用相同的组件,因此不会重新创建一个新的组件Vue中的生命周期如:created只能创建一次。
解决: 为了响应参数的变化,我们可以再created中监听属性;或者使用路由监听的生命周期钩子

  • created监听
const User = { 
  template: '#user',
   created() {
       this.$watch(() => this.$route.params,
       (toParams, previousParams) => {
           // to:目标参数
           // previous:之前的参数
           console.log(toParams, previousParams);
       })
   }
}
  • 生命周期钩子
const User = { 
   template: '#user',
   beforeRouteUpdate(to, from) {
       console.log(to.path, from);
   }
}

在这里插入图片描述

3. 多级路由

在这里插入图片描述
类似的,在第一级路由下的内容中,可以继续引入其他的a标签,提供内容跳转的功能

点击若干跳转后的内容组件,然后修改router的配置文件

import MessageOne from '../pages/MessagesOne'
import MessageTwo from '../pages/MessagesTwo'   // 导入组件

export default new VueRouter({
    routes: [
        {
            path: '/about',
            component: About,
            children: [
                {
                    path: 'message_one',
                    component: MessageOne
                },
                {
                    path: 'message_two',
                    component: MessageTwo
                }
            ]
        },
        {
            path: '/home',
            component: Home
        }
    ]
})

在一级路由内容下面修改模板:

<template>
    <div>
        <div>我是About的内容</div>
        <ul>
            <li><router-link to="/about/message_one">message1</router-link></li>
            <li><router-link to="/about/message_two">message2</router-link></li>
        </ul>
        <router-view></router-view>
    </div>
   
</template>

子路由的跳转规则中不需要加 /
在html中内容的跳转需要写上完整的路径信息

4. 路由传参

场景描述: 在三级路由的情况下,为了避免大量Vue组件的定义,可以将信息中通用的信息进行复用,利用参数进行消息定制
在这里插入图片描述
实现
首先修改路由配置:

import Details from '../pages/Details'  // 引入新的组件

export default new VueRouter({
    routes: [
        {
            path: '/about',
            component: About,
            children: [
                {
                    path: 'message_one',
                    component: MessageOne,
                    children: [
                        {
                            path: 'child_msg',  // 三级路由
                            component: Details
                        }
                    ]
                },
                {
                    path: 'message_two',
                    component: MessageTwo
                }
            ]
        }
    ]
})

二级路由中消息的定义,使用v-for遍历数组动态生成信息

<template>
  <div>
    <ul>
      <li v-for="item in dataList" :key="item.id"> 
        <router-link 
        :to="{
            path: '/about/message_one/child_msg',
            query: {
                id: item.id
            }
        }">
        id:{{ item.id }} {{ item.title }}</router-link>
      </li>
    </ul>
    <router-view></router-view>
  </div>
</template>
<script>
export default {
  name: "MessageOne",
  data() {
    return {
      dataList: [  // 数据管理
        { id: 1, title: "消息1" },
        { id: 2, title: "消息2" },
        { id: 3, title: "消息3" },
      ],
    };
  },
};
</script>

其中注意传参的写法:

:to="{
           path: '/about/message_one/child_msg',
           query: {   // 参数传递
              id: item.id
           }
     }">

details中如何获取参数?
在跳转组件的 r o u t e 中绑定了当前组件的路由跳转信息, t h i s . route中绑定了当前组件的路由跳转信息, this. route中绑定了当前组件的路由跳转信息,this.route
在这里插入图片描述
因此可以写出下面的代码:

<template>
    <div>
        我是消息 {{ $route.query.id }}
    </div>
</template>

5. 路由props

在之前写的时候,{{ $route.query.id }} 当属性过多的时候,在模板中就会显的很冗余;因此可以使用props将参数赋值给组件中的变量,将代码解耦到配置文件中
修改路由配置文件

children: [
	{
        path: 'message_one',
        component: MessageOne,
        children: [
            {
                path: 'child_msg',
                component: Details,
                props($route) {  // 这里,直接通过回调参数可以拿到$route
                    return {
                        id: $route.query.id
                    }
                }
            }
        ]
    },
    {
        path: 'message_two',
        component: MessageTwo
    }
]

在组件中获取:

<script>

export default ({
    name: 'DatailsPage',
    props: ['id'],
    mounted() {
        console.log(this.$route)  
    }
})
</script>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值