vue-router用于实现页面的跳转,例如点击Home按钮,进入Home页面,点击About按钮,进入About页面
一、基本路由
1.在src中新建两个vue文件,分别为home.vue和about.vue
<template>
<div>
<h1>Home</h1>
<p>{{msg}}</p>
</div>
</template>
<script>
export default {
data() {
return {
msg: "这是Home页"
};
}
};
</script>
<template>
<div>
<h1>About</h1>
<p>{{msg}}</p>
</div>
</template>
<script>
export default {
data() {
return {
msg: "这是About页"
};
}
};
</script>
2.在App.vue中定义<router-link>和<router-view>
<template>
<div id="app">
<img src="./assets/logo.png">
<header>
<router-link to="/home">Home</router-link>
<router-link to="/About">About</router-link>
</header>
<router-view/>
</div>
</template>
3.在index.js中定义路由,一组路由包含path和component两部分,vue通过比对path,跳转到相应的component
import Vue from 'vue'
import Router from 'vue-router'
import home from '../components/home.vue'
import about from '../components/about.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/home',
component: home,
},
{
path: '/about',
component: about
}
]
})
4.把路由注入到根实例
import Vue from 'vue'
import App from './App'
import router from './router'
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
5.redirect 定义重定向,首次进入页面路径是'/',页面没有显示任何内容,使用重定向能使页面首次加载就会显示home页面
export default new Router({
routes: [
{
path: '/home',
component: home,
},
{
path: '/about',
component: about
},
{
path: '/',
redirect: '/home'
}
]
})
二、动态路由
1.在App.vue添加两个<router-link>
<router-link to="/user/123">User123</router-link>
<router-link to="/user/456">User456</router-link>
2.在index.js中配置动态路由
export default new Router({
routes: [
{
path: '/home',
component: home,
},
{
path: '/about',
component: about
},
{
path: '/user/:id',
component: user
},
{
path: '/',
redirect: '/home'
}
]
})
记得将组件导入进来
import user from '../components/user.vue'
3.添加user.vue组件
<template>
<div>
<h1>User</h1>
<div>User组件,动态部分是{{dynamicSegment}}</div>
</div>
</template>
<script>
export default {
computed: {
dynamicSegment() {
return this.$route.params.id;
}
}
};
</script>
computed定义dynamicSegment属性,用于获取动态id
三、嵌套路由
1.在home.vue中添加<router-link>
<template>
<div>
<h1>Home</h1>
<!-- <p>{{msg}}</p> -->
<p>
<router-link to="/home/phone">手机</router-link>
<router-link to="/home/tablet">平板</router-link>
<router-link to="/home/computer">电脑</router-link>
</p>
<router-view></router-view>
</div>
</template>
2.在index.js定义路由
export default new Router({
routes: [
{
path: '/home',
component: home,
children:[
{
path: 'phone',
component: phone
},
{
path: 'tablet',
component: tablet
},
{
path: 'computer',
component: computer
},
//当进入到home时,显示默认组件
{
path: '',
component: phone
}
]
},
{
path: '/about',
component: about
},
{
path: '/user/:id',
component: user
},
{
path: '/',
redirect: '/home'
}
]
})
3.添加phone.vue,tablet.vue,computer.vue组件
以phone.vue为例
<template>
<div>
<h2>Phone</h2>
<p>{{msg}}</p>
</div>
</template>
<script>
export default {
data() {
return {
msg: "这是Phone页"
};
}
};
</script>
贴上目录结构图
【参考文章】
vue-router基本使用:https://www.cnblogs.com/SamWeb/p/6610733.html