美文网首页
Vue Router路由用法

Vue Router路由用法

作者: sunpy | 来源:发表于2025-01-17 00:28 被阅读0次

安装Vue Router


npm install 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
  • 2、携带参数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
  • 2、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栈中不会有记录,点击返回会跳转到上上个页面 (就是直接替换了当前页面)

相关文章

网友评论

      本文标题:Vue Router路由用法

      本文链接:https://www.haomeiwen.com/subject/fzulsjtx.html