构建项目
- vue init webpack vue-router-demo
- cnpm install
使用vue-router
1. 在src文件夹下 -- 新建router文件夹 -- 新建index.js
2. 在index.js中引入vue、vue-router
- import Vue from 'vue'
- import VueRouter from 'vue-router'
- Vue.use(VueRouter)
3. 在index.js中声明一个VueRouter实例
- export default new VueRouter({ routes: [ { path:'/home', component: Home } ] })
4. 在main.js中引入router、并在new Vue({}) 实例中添加router
- import router from './router'
- new Vue({router})
5. 通过<router-view></router-view>显示
6. router-link
- <router-link to="/home">Home</router-link>
- <router-link :to="{path:'/home'}">Home</router-link>
- <router-link :to="{name:'home'}">Home</router-link>
- <router-link :to="{name:'home'}" tag="li">Home</router-link> 把<router-link></router-link> 渲染成li标签
eg:
- App.vue
<template> <div id="app"> <div>我是APP</div> <a href="#/home">Home</a> // 这里的地址要写 #/ 或者给index.js中的VueRouter实例配置一个mode字段 mode:'history'(这个字段会刷新页面) <a href="#/about">About</a> <li><router-link to="/home">Home</router-link></li> <li><router-link to="/doc">Doc</router-link></li> <li><router-link to="/about">About</router-link></li> <router-view></router-view> </div> </template> <script> export default { name: 'App' } </script>
eg:
- index.js
import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../components/home.vue' import About from '../components/about.vue' Vue.use(VueRouter) export default new VueRouter({ routes: [ { path:'/home', name: 'home', // 如果路由很深,用name会方便一些 component: Home }, { path:'/about', component: About } ] })
eg:
- main.js
import Vue from 'vue' import App from './App' import router from './router' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })
eg:
- home.js
<template> <div>我是{{title}}</div> </template> <script> import Home from '../components/home' export default { data() { return { title: 'HOME' } } } </script>
eg:
- about.js
<template> <div>我是{{title}}</div> </template> <script> import About from '../components/about' export default { data() { return { title: 'ABOUT' } } } </script>