通过vue-cli模块化工程开发
1.先安装路由模块
npm install vue-router --save-dev
2.重启vue
3.在main.js中引入路由模块
import VueRouter form 'vue-router'
4.在main.js中使用路由
Vue.use(VueRouter)
5.在main.js中配置路由
const router = new VueRouter({
routes:[
{path:"/",component:Home},
{path:"/helloworld",component:HelloWorld}
],
mode:"history" // 去掉url链接中的#号
})
6.在main.js中引入Home,HelloWorld组件
import Home from '.components/Home'
import HelloWorld from '.components/HelloWorld'
7.在实例化Vue中使用router
new Vue({
router,
el:'#app',
template:'<App/>',
components:{ App }
})
8.在App根组件里面展示
<ul>
<li><a href="/">Home</a></li>
<li><a href="/helloworld">Hello</a></li> // 会刷新页面
<li><router-link to="/">Home</router-link></li> // 不会刷新页面
<li><router-link to="/helloworld">Hello</router-link></li>
</ul>
<router-view></router-view>
直接引入cdn开发
<div id="app">
<div class="row">
<div class="col-xs-8 col-xs-offset-2">
<div class="page-header">
<h1>IT教育</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-2 col-xs-offset-2">
<div class="list-group">
<router-link class="list-group-item" to="/h5">HTML5学院</router-link>
<router-link class="list-group-item" to="/java">JAVA学院</router-link>
<router-link class="list-group-item" to="/python">PYTHON学院</router-link>
</div>
</div>
<div class="col-xs-6">
<div class="panel">
<div class="panel-body">
<router-view></router-view>
</div>
</div>
</div>
</div>
</div>
<template id="h5">
<div>
<h1>Html5学院</h1>
<p>掌握面向未来的神技</p>
<div>
<ul class="nav nav-tabs">
<!-- <router-link to="/h5/basic">基础班</router-link>
<router-link to="/h5/big">大神班</router-link> -->
<router-link :to="{name:'basic'}">基础班</router-link>
<router-link :to="{name:'big'}">大神班</router-link>
</ul>
<div class="tab-content">
<router-view></router-view>
</div>
</div>
</div>
</template>
<template id="basic">
<div>
<h2>基础班</h2>
<p>快速入门h5的学习</p>
</div>
</template>
<template id="big">
<div>
<h2>精通h5的学习</h2>
<p>掌握面向未来的神技</p>
</div>
</template>
<template id="java">
<div>
<h2>Java学院</h2>
<p>都说java是最好的语言</p>
</div>
</template>
<template id="python">
<div>
<h2>Python学院</h2>
<p>很火热的语言</p>
</div>
</template>
<script src="js/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script>
// 创建组件
const Html5 = Vue.extend({
template: '#h5'
})
const Basic = Vue.extend({
template: '#basic'
})
const Big = Vue.extend({
template: '#big'
})
const Java = Vue.extend({
template: '#java'
})
const Python = Vue.extend({
template: '#python'
})
// 定义路由
const routes = [{
path: '/h5',
component: Html5,
children: [{
path: 'basic',
component: Basic,
name: 'basic'
}, {
path: 'big',
component: Big,
name: 'big'
}, {
path: '/',
redirect: 'basic'
}]
}, {
path: '/java',
component: Java
}, {
path: '/python',
component: Python
}, {
path: '/',
redirect: '/h5'
}]
// 创建路由实例
const router = new VueRouter({
routes
})
//创建vue实例并挂载
new Vue({
router
}).$mount('#app')
</script>