app.vue
<template>
<div id="app">
<router-link to="/home">首页</router-link>
<router-link to="/about">关于</router-link>
<button @click="userClick">用户</button>
<button @click="proClick">档案</button>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return{
userId:'geyao'
}
},
methods:{
userClick(){
this.$router.push('/user/'+this.userId)
},
proClick(){
this.$router.push({
path:'/pro',
query:{
name:'geyao',
age:18
}
})
},
}
}
</script>
<style>
</style>
Home.vue
<template>
<div>
<h2>
我是首页
</h2>
<p>我是首页内容</p>
<router-link to="/home/news">新闻</router-link>
<router-link to="/home/message">新闻</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default{
name:"Home"
}
</script>
<style scoped>
</style>
about.vue
<template>
<div>
<h2>
我是about
</h2>
<p>我是首页内容</p>
</div>
</template>
<script>
export default{
name:"Home"
}
</script>
<style scoped>
</style>
User.vue
<template>
<div>
<h2>
我是user
</h2>
<p>我是首页内容</p>
<h2>{{userId}}</h2>
</div>
</template>
<script>
export default{
name:"User",
computed:{
userId(){
return this.$route.params.userId
}
}
}
</script>
<style scoped>
</style>
HelloWorld.vue
<template>
<div>
<h2>
我是about
</h2>
<p>我是首页内容</p>
<p>我是首页内容</p>
<p>我是首页内容</p>
<p>我是首页内容</p>
<ul>
<li>
1
</li>
</ul>
</div>
</template>
<script>
export default{
name:"Home"
}
</script>
<style scoped>
</style>
index.js
import VueRouter from 'vue-router'
import Vue from 'vue'
import Home from '../components/Home'
import About from '../components/About'
import User from '../components/User'
import HomeNew from '../components/HelloWorld'
import HomeMessage from '../components/Hello'
import Profile from '../components/Profile'
Vue.use(VueRouter)
const routes = [{
path: '/',
redirect: '/home'
}, {
path: '/home',
component: Home,
children: [{
path: 'news',
component: HomeNew
},
{
path: 'message',
component: HomeMessage
},
]
},
{
path: '/about',
component: About
},
{
path: '/pro',
component: Profile
},
{
path: '/user/:userId',
component: User,
meta: {
title: '用户'
}
},
]
//安装插件
const router = new VueRouter({
//配置之间的关系
routes,
mode: 'history',
linkActiveClass: 'active'
})
router.beforeEach((to, from, next) => {
next()
document.title = to.meta.title
})
export default router
Hello.vue
<template>
<div>
<h2>
我是about
</h2>
<p>我是首页内容</p>
</div>
</template>
<script>
export default{
name:"Home"
}
</script>
<style scoped>
</style>
profile.vue
<template>
<div>
<h2>
我是pro
</h2>
<p>我是首页内容</p>
<p>{{$route.query.name}}</p>
<p>{{$route.query.age}}</p>
</div>
</template>
<script>
export default{
name:"Home"
}
</script>
<style scoped>
</style>
运行结果