安裝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棧中不會有記錄,點擊返回會跳轉到上上個頁面 (就是直接替換了當前頁面)