一、创建项目
这里用vue-cli创建项目,创建过程可以参考vue-cli快速构建项目,创建完成后生成如下工程目录:
二、项目目录
三、配置路由Router
在项目创建的过程中,Install vue-router? 如果选择了Yes,项目目录的src下就会自动生成一个router的文件夹,index.js就是vue-cli自动构建的router的配置文件,路由设置就在这里面配置,但如果创建项目的时候,选择了no,就不会自动生成router文件夹,就需要手动创建,然后进行配置。
用vue-cli创建项目的初始模板里面,node_modules文件夹下如果没有vue-router,需要重新npm安装
npm install vue-router --save
如下是router的配置文件信息:mode:'history' 是让浏览器记住url路径,前进和后退能够记住历史信息,redirect是设置路由的默认显示,子路由通过children来设置。
(1)src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Apple from '@/components/apple'
import Banana from '@/components/banana'
import Apple1 from '@/components/Apple1'
import Apple2 from '@/components/Apple2'
Vue.use(Router)
export default new Router({
mode:'history',
routes: [
{
path: '/',
redirect: 'helloworld'
},
{
path: '/helloworld', //path为路径
name: 'HelloWorld', //name配置名字,这个name是跟对应的.vue中的name相对应
component: HelloWorld
},
{
path: '/apple',
name: 'Apple',
component: Apple,
children:[
{
path:'apple1',
name:'Apple1',
component:Apple1
},
{
path:'apple2',
name:'Apple2',
component:Apple2
}
]
},
{
path: '/banana',
name: 'Banana',
component: Banana
}
]
})
(2)src/App.vue
<template>
<div id="app">
<div>
<img src="./assets/logo.png">
</div>
<div>
<router-view></router-view>
</div>
<div>
<router-link :to="{path:'/apple'}">Apple</router-link>
<router-link :to="{path:'/banana'}">Banana</router-link>
<router-link :to="{path:'/helloworld'}">HelloWorld</router-link>
</div>
</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>
(3)src/components/apple.vue
<template>
<div>
<div>
{{msg}}
</div>
<div>
<router-view></router-view>
</div>
<div>
<router-link :to="{path:'/apple/apple1'}">apple1</router-link>
<router-link :to="{path:'/apple/apple2'}">apple2</router-link>
</div>
</div>
</template>
<script>
export default{
name:'Apple', //跟路由里面的配置相对应
data(){
return {
msg: 'hello apple'
}
}
}
</script>
<style>
</style>
效果如下图所示: