11.0、vue-router路由
第一步:安装vuerouter,要在当前项目下的控制台执行这段命令行
用npm install vue-router --save-dev
第二步:导入vue-router
import VueRouter from 'vue-router'
//显示声明使用VueRouter
Vue.use(VueRouter);
由于这里npm-router安装后一直报错无法运行,好像是版本的问题。所以我直接重新创建了一个新项目,并且在创建项目的时候,勾选自动下载npm-router
第三步:在components文件夹下创建一个自己的组件Main.vue
<template>
<h1>首页</h1>
</template>
<script>
export default {
name: 'Main'
}
</script>
<style scoped>
</style>
再创建一个Content.vue组件
<template>
<h1>内容页</h1>
</template>
<script>
export default {
name: 'Content'
}
</script>
<style scoped>
</style>
第四步:在router文件夹下创建一个路由配置文件index.js
import Vue from 'vue'
import Router from 'vue-router'
import Content from '../components/Content'
import Main from '../components/Main'
//安装路由
Vue.use(Router)
export default new Router({
routes: [
{
// 路由路径
path: '/content',
name: 'content',
// 跳转的组件
component: Content
},
{
// 路由路径
path: '/Main',
name: 'Main',
// 跳转的组件
component: Main
}
]
})
第五步:在main.js文件中配置一下路由
import Vue from 'vue'
import App from './App'
//这里会自动扫描router文件夹下的js路由配置文件并导入过来
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
// 配置路由
router,
components: { App },
template: '<App/>'
})
第六步:在app.vue中加入Main组件和Content组件测试路由是否可用即可
<template>
<div id="app">
<router-link to="/Main">首页</router-link>
<router-link to="/Content">内容页</router-link>
<router-view/>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
总结一下:
这些文件之间的关系,首先解释一下main.js里的代码如下:
整个router路由流程其实就是:先创建了两个组件分别是主页和内容页,然后在router路由
index.js文件里注册一下路径和要跳转的组件,最后在App组件中加上需要的组件即可。