blog前提
要想看懂这篇bolg,你要会操作一下的知识
- 你会在vue里面创建一个简单的html文件,甚至不需要css或者说明东西。
- 你会创建vue项目,会看vue文件夹
什么是路由
我们可以知道,一个网站肯定需要很多的页面的。实现这些页面实现一个跳转的功能就叫路由。
比如,你在看B站的时候,突然想看电影了,然后你从主页面点击电影这个按钮
网址从 https://www.bilibili.com 变到了 https://www.bilibili.com/movie/?spm_id_from=333.1007.0.0
页面也发生了变化,这个过程就叫做路由
步骤
安装Vue Router
npm install vue-router
创建页面
我们可以手动创建多个页面组件,然后通过 Vue Router 进行管理和导航,其中基础模板是
Example.vue
这些文件一般放在components里面的文件夹中
<template>
<div>
你的页面内容
</div>
</template>
<script>
export default {
name: 'HomePage' //
}
</script>
<style>
/* CSS样式 */
</style>
这个只是一个路由功能的介绍。
创建router文件
./src/router/index.js
这里面我创建了三个页面, 分别是HomePage.vue、CoursesPage.vue、AboutPage.vue
index 里面的文件就是你所有路由的文件都要包括在里面
其中
import Vue from 'vue';
import Router from 'vue-router';
import HomePage from '../components/HomePage.vue';
import CoursesPage from '../components/CoursesPage.vue';
import AboutPage from '../components/AboutPage.vue';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'home',//这两行代码意思就是这个网页放在来 /home里面
component: HomePage
},
{
path: '/courses',
name: 'courses',
component: CoursesPage
},
{
path: '/about',
name: 'about',
component: AboutPage
}
]
});
补充代码
这里面你要补充 main.js 和app.vue里面的代码
main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
Vue.config.productionTip = false;
new Vue({
router,
render: h => h(App)
}).$mount('#app');
app.vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App'
};
</script>
<style>
/* 可选的样式 */
</style>