当前位置: 代码迷 >> 综合 >> Vue3.0 Router 路由
  详细解决方案

Vue3.0 Router 路由

热度:41   发布时间:2023-12-06 14:30:32.0

  由于Vue在 开发时对路由支持的不足,于是官方补充了vue-router插件。vue的单页面应用是基于路由和组件的,路由用于设定访问路径,并将路径和组件映射起 来。传统的页面应用,是用一些超链接来实现页面切换和跳转的。在vue-router单页面应用中,则是路径之间的切换,实际上就是组件的切换。路由就是 SPA(单页应用)的路径管理器。再通俗的说,vue-router就是我们WebApp的链接路径管理系统。

1,router-link(页面跳转)

我们没有使用常规的 a 标签,而是使用一个自定义组件 router-link 来创建链接。这使得 Vue Router 可以在不重新加载页面的情况下更改 URL,处理 URL 的生成以及编码。

  • <router-link to="/about">

<template><div id="main"><router-view class="views has-tabs" /><div class="tabs"><router-link class="links ihome" to="/">首页</router-link><router-link class="links icate" to="/category">分类</router-link><router-link class="links iball" to="/ball">米圈</router-link><router-link class="links icart" to="/cart">购物车</router-link><router-link class="links iuser" to="/user">我的</router-link></div></div>
</template>

2,router-view

router-view 将显示与 url 对应的组件。你可以把它放在任何地方,以适应你的布局。


3,router/index.j 路由配置

        {
path:"/about",
name:"About",
component:About
}


4,路由传参

:冒号的形式传递参数如图

//引入文件
import User from '../views/User.vue'
import Produce from '../views/Produce.vue'
//定义路由
const routes = [{path: '/',name: 'home',component: HomeView},{path: '/produce/:id',name: 'produce',component: Produce}
]

接收 

<template><p>我是产品页面</p><p>{
   {$route.params.id}}</p>
</template>

5,$router 编程路由跳转

  • 后退  back()  ,go(-1)
  • 前进 forword() ,go(1)
  • 跳转 push()
  • 替换 replace()
<template><div><h1>我是产品页面</h1><p>{
   {$route.params.id}}</p><h3>通过js方式跳转页面</h3><button @click="$router.back()">返回</button><button @click="$router.go(-1)">返回</button><button @click="$router.forward()">前进</button><button @click="$router.go(1)">前进</button><hr ><button @click="$router.push('/about')">关于</button><button @click="$router.replace('/about')">关于,不留历史记录:替换</button></div>
</template>

  相关解决方案