之前的组件部分学习告一段落,紧接着就到了最关键也是(据说)最恶心的路由部分。
废话不多说,进入正题。
一、安装
1.最简单的方法就是在页面直接引入vue-router文件:
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
这种方式适合初学者了解和快速上手小demo。
2.通过npm安装:
npm install vue-router
按照历史惯例,国内npm安装存在墙的问题,用淘宝源或者vpn解决。
此处还有另外一个坑,就是从github或其他地方下载好别人的开源项目,依次输入npm install, npm run dev,跑出来会报错找不到vue-router
博主第一次碰到这种问题百思不得其解,后来打开项目中的package.json文件,找到"dependencies",发现其中居然没有vue-router!
遂执行npm install vue-router -s 安装vue-router依赖,最后成功解决这个卡了好几天的bug。
不知道是不是所有新下的项目都需要有这步操作,希望有高人可以告知。
二、开始
在项目main.js文件中引入vue-router:
import VueRouter from 'vue-router'
Vue.use(VueRouter);
来看一个 官方例子:
App.vue:
<template>
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- 使用 router-link 组件来导航. -->
<!-- 通过传入 `to` 属性指定链接. -->
<!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>
</template>
这里官方注释非常清楚,router-link标签用to属性来作为链接地址,路由渲染出来的结果会在router-view中显示,
值得一提的是渲染结果是直接取代router-view标签,而不是作为子标签,这点新手要注意。
main.js:
// 1. 定义(路由)组件。
// 可以从其他文件 import 进来
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
// 2. 定义路由
// 每个路由应该映射一个组件。
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
// 3. 创建 router 实例,然后传 `routes` 配置
const router = new VueRouter({
routes // (缩写)相当于 routes: routes
})
// 4. 创建和挂载根实例。
const app = new Vue({
router
}).$mount('#app')
基本上实现vue-router的过程可以分为这么4步,不过由于实现方式的不同,可以简化:
import routeConfig from './route-config'//将route-config文件放在和main.js同一级目录下,再在main.js里写上
const router = new VueRouter({
routes: route-config
})
export default {
{
path: '/foo', component: { template: '<div>This is foo.</div>' }
},
{
path: '/bar', component: { template: '<div>This is bar.</div>' }
}
}
更工程化一点的做法是将路由的组件们也单独放入文件,用的时候再调用,便于修改:
foo.vue:
<template>
<div>
<div>This is foo.</div>
</div>
</template>
bar.vue:
<template>
<div>
<div>This is bar.</div>
</div>
</template>
route-config.js:
import Foo from './components/foo.vue'
import Bar from './components/bar.vue'
export default [
{
path: '/foo', components: Foo,
{
path: '/bar', components: Bar
}
]
最后挂载根目录:
const app = new Vue({
router,//router: router
render: h => h(App)
}).$mount('#app')
基础部分就先到这里,之后会带来更多vue-router的深入内容。