vue-router用法

配置vue-router的路由

import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/login/index.vue'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },
    {
      path: '/home',
      name: 'Home',
      component: () => import('@/views/home/index.vue')
    }
  ]
})

第一种,router-link跳转

不带参数跳转

## 直接跳转
<router-link tag="div" to="/home">跳转到Home页</router-link>
## 使用name跳转

## 使用匹配名称跳转
<router-link tag="button" :to="{name:'Home'}">跳转到Home页</router-link>
## 使用匹配路径跳转
<router-link tag="button" :to="{path:'/home'}">跳转到Home页</router-link>

带参数跳转

  1. 携带参数params,需要配置路由
export default new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },
    {
      path: '/home/:id',
      name: 'Home',
      component: () => import('@/views/home/index.vue')
    }
  ]
})

## 原页面
<router-link tag="button" :to="{name:'Home', params: {id:1}}">跳转到Home页</router-link>

## 跳转后的页面
html获取参数:$route.params.id
js获取参数:this.$route.params.id
  1. 携带参数query,无需配置路由
## 原页面
<router-link tag="button" :to="{name:'Home', query: {id:1}}">跳转到Home页</router-link>

## 跳转后的页面
html获取参数:$route.query.id
js获取参数:this.$route.query.id

第二种,this.$router.push跳转

无参数跳转

<el-button type="primary" @click="submitForm">
	跳转到Home页
</el-button>

submitForm() {
	this.$router.push('/home')
}

有参数跳转

  1. query传参数跳转,无需配置路由
submitForm() {
	this.$router.push({name:'Home',query: {id:'1'}})
}

## 跳转后的页面
html获取参数:$route.query.id
js获取参数:this.$route.query.id
  1. params传参数跳转,需要配置路由
## 配置路由
export default new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },
    {
      path: '/home/:id',
      name: 'Home',
      component: () => import('@/views/home/index.vue')
    }
  ]
})

## 跳转
this.$router.push({name:'Home', params: {id:'1'}})

## 跳转后的页面
html获取参数:$route.params.id
js获取参数:this.$route.params.id

第三种,this.$router.replace()跳转

用法和this.$router.push一样。

this.$router.push
跳转到指定url路径,并想history栈中添加一个记录,点击后退会返回到上一个页面

this.$router.replace
跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上上个页面 (就是直接替换了当前页面)

参考

https://www.jb51.net/article/160401.htm
https://www.php.cn/faq/483468.html

posted @ 2023-07-03 21:39  sunpeiyu  阅读(23)  评论(0编辑  收藏  举报