vue-router 路由
- 当前项目下 npm install vue-router --save-dev
- npm install vue-router 安装路由
- –save-dev 保存在dev的配置中
使用方法
项目目录结构

1.定义组件
自定义组件Content.vue和Main.vue
Content.vue
<template>
<h1>内容页</h1>
</template>
<script>
export default { //导出 让外部能够使用import导入
name: "Content"
}
</script>
<style scoped>
</style>
Main.vue
<template>
<h1>首页</h1>
</template>
<script>
export default {
name: "Main"
}
</script>
<style scoped>
</style>
2.配置路由
index.js
import Vue from 'vue';
import VueRouter from "vue-router"; //导入路由
import Content from '../components/Content'; //导入组件
import Main from '../components/Main';
//安装路由
Vue.use(VueRouter);
//配置路由
export default new VueRouter({
routes: [
{
//路由的路径 请求的路径
path: '/content',
name: 'Content',
//跳转的组件
component: Content
},
{
path: '/main',
name: 'Main',
component: Main,
}
]
});
3.在APP.vue中展示
<template>
<div id="app">
<router-link to="/main">首页</router-link> <!--控制跳转 相当于html中的a链接-->
<router-link to="/content">内容页</router-link>
<router-view></router-view> <!--控制页面的展示,将请求对应模板的内容展示在标签的位置-->
</div>
</template>
<script>
export default {
name: 'App',
components: {
}
}
</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>
4main.js中导入路由配置
import Vue from 'vue'
import App from './App'
import router from './router' //自动扫描里面的路由配置 默认扫描index文件
Vue.config.productionTip = false;
/* eslint-disable no-new */
new Vue({
el: '#app',
//配置路由
router,
components: { App },
template: '<App/>'
})
测试

本文介绍了如何在Vue项目中使用vue-router进行路由配置。首先通过npm安装vue-router,然后定义组件如Content.vue和Main.vue。接着在index.js中配置路由,最后在APP.vue和main.js中完成路由的导入和展示。测试环节验证了路由功能的正确性。
595

被折叠的 条评论
为什么被折叠?



