跳轉(zhuǎn)方式
第一種:普通跳轉(zhuǎn)
<template>
<div id="app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view />
</div>
</template>
<script>
export default {
name: 'App',
methods: {
linkToHome () {
this.$router.push('./')
},
linkToAbout () {
this.$router.push('./about')
}
}
}
</script>
第二種:代碼跳轉(zhuǎn)
<template>
<div id="app">
<div id="nav">
<button @click="linkToHome">首頁(yè)</button>
<button @click="linkToAbout">關(guān)于</button>
</div>
<router-view />
</div>
</template>
<script>
export default {
name: 'App',
methods: {
linkToHome () {
this.$router.push('./')
},
linkToAbout () {
this.$router.push('./about')
}
}
}
</script>
都要定義路由文件:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
const router = new VueRouter({
routes
})
export default router
動(dòng)態(tài)路由
{
path: '/user/:id',
name: 'User',
component: () => import('../views/User.vue')
}
// User組件
<template>
<div>
<p>User {{ $route.params.id }}</p>
</div>
</template>
<script>
export default {
}
</script>
// App.vue
<template>
<div id="app">
<div id="nav">
<router-link :to="'/user/'+id">User</router-link>
</div>
<router-view />
</div>
</template>
<script>
export default {
name: 'App',
data () {
return {
id: 'lili'
}
}
}
</script>
路由懶加載
vue-cli4腳手架的代碼已經(jīng)有懶加載路由
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
},
子路由
{
path: '/user/:id',
name: 'User',
component: () => import('../views/User.vue'),
children: [
{
path: '/user/:id/content',
component: () => import('../views/User_content.vue')
}
]
}