router-link和router-view

tech2026-03-14  4

router-link 标签

<router-link to='./home'></router-link> //vue 内置标签 在渲染时渲染成a标签在点击的情况路由中的页面在<router-view>标签中渲染 to属性可以跳转页面 tag="button" 属性可以渲染成想要的原生标签

类似a标签

<a href="#/User">用户管理1</a> <router-link to="/user"> 用户管理2</router-link>

这里写法需要在router中配置

router-view标签

<router-view></router-view>写在组件想要渲染的地方,等组件跳转过来就渲染

路由的参数传递

 

<template> <div id="app"> //active-class="active"改变他动态添加的名字 //replace 不能返回 直接写在标签内 默认事pushState 可以返回 <router-link to = '/home' tag="button" replace active-class="laozhang">首页</router-link> <router-link to = "/about" tag="button" replace active-class="laozhang">关于</router-link> <button @click="fn1">首页</button> <button @click="fn2">关于页</button> //hash嘻哈值数据 <router-link :to = "'/user/'+userId" tag="button" replace active-class="laozhang">用户</router-link> //查询串数据 <router-link :to = "{path:'/profile',query:{name:'laowang',age:18}}" tag="button" replace active-class="laozhang">用户</router-link> <router-link @click="fn3" tag="button" >档案</router-link> <router-view> </router-view> </div> </template> <script> export default { name: 'app', data(){ return { $router:'', userId:'lisi' } }, methods:{ fn1(){ //this.$router拿到当前页面的url通过push拼接url,push进去的浏览器可以返回原页面 this.$router.push('/home') }, fn2(){ this.$router.push('/about') }, fn3(){ this.$router.push({//将数据携带在url上 path:'/profile', query:{//查询串数据 name:'laowang', age:18 } }) } } } </script> <style> @import"assets/css/base.css"; .laowang{ color: aquamarine; } .laozhang{ background: rgb(221, 49, 49); } </style>

数据获取

通过url访问组件的时候将数据带到了组件,在组件中渲染

 

<template> <div> <h2>我是用户界面</h2> <p>我是用户相关信息,呵呵呵</p> <h2>{{userId}}</h2> <h2>{{$route.params.userId}}</h2> </div> </template> <script> export default { name:'User', computed:{ userId(){//计算属性, $route拿到的是活越的路由params数参数//$route是我们new的router路由 return this.$route.params.userId } } } </script>>

query数据接收

 

<template> <div> <h2>我的组件</h2> <p>地址,浏览历史</p> <h2>{{$route.query.name}}</h2> <h2>{{$route.query.age}}</h2> <h2>{{Obj.name}}</h2> </div> </template> <script> export default { name:'profile', computed:{ userId(){//计算属性, $route拿到的是活越的路由params数参数//$route是我们new的router路由 return this.$route.params.userId }, Obj(){ return this.$route.query } } } </script>>

 

最新回复(0)