app.vue
<template>
<div id="app">
<router-link to="/home">首页</router-link>
<router-link to="/about">关于</router-link>
<router-link v-bind:to="'/user/'+userId">用户</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return{
userId:'geyao'
}
},
methods:{
}
}
</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'
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: '/user/:userId',
component: User
},
]
//安装插件
const router = new VueRouter({
//配置之间的关系
routes,
mode: 'history',
linkActiveClass: 'active'
})
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>
运行结果