跳转方式
第一种:普通跳转
<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>
第二种:代码跳转
<template>
<div id="app">
<div id="nav">
<button @click="linkToHome">首页</button>
<button @click="linkToAbout">关于</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
动态路由
{
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脚手架的代码已经有懒加载路由
{
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')
}
]
}