接上一篇搭建好结构的基础上,安装vue-router
cnpm install vue-router
src目录下添加Content.vue,Date.vue和route.js
//Date.vue
<template>
<div>
<p>{{name}}</p>
</div>
</template>
<script>
export default {
name:'date',
computed:{
name(){
return 'date'
}
},
methods:{
},
mounted(){
}
}
</script>
<style>
*{margin:0;padding:0;}
p{margin:10px 0;background:#eee;}
</style>
//Content.vue
<template>
<div>
<p>{{name}}</p>
</div>
</template>
<script>
export default {
name:'Content',
computed:{
name(){
return 'content'
}
},
methods:{
},
mounted(){
}
}
</script>
<style>
*{margin:0;padding:0;}
p{margin:10px 0;background:#eee;}
</style>
//route.js
import Vue from 'vue'
import Router from 'vue-router'
import Da from './Date.vue'
import Content from './Content.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/content',
component: Content
},
{
path: '/date',
component: Da
}
]
})
App.vue template结构改成
<template>
<div>
<router-link to="/content">content</router-link>
<router-link to="/date">date</router-link>
<router-view></router-view>
</div>
</template>
main.js引入route.js,并注入模块中
//Main.js
import Vue from 'vue';
import App from './App.vue';
import router from './route'
new Vue({
el:'#app',
router,
components: {App},
render: h => h(App),
mounted:function(){console.log('hello world')}
})
至此简单的路由功能已经搭建完成。组件中可以通过this.$router和this.$route访问路由器和当前路由。
要使用动态路由,例如date/xiaogang,只需要将router-link链接改成需要的
<router-link to="/date/xiaogang">date</router-link>
route.js
{
path: '/date/:name',
component: Da
}
Date.vue,使用this.$route.params.name就能获取到对应数据
computed:{
name(){
return this.$route.params.name
}
},
关于重定向,只要设置redirect,默认跳转content组件
{
path: '/',
redirect:'/content',
component: Content
}