vue 中简单路由的实现

   vue 中简单路由的实现

1. 引入vue-router,如果是在脚手架中,引入VueRouter之后,需要通过Vue.use来注册插件
```
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
```
2. 创建router路由器
```
new Router(options)
```
3. 创建路由表并配置在路由器中
```
var routes = [
{path,component}//path为路径,component为路径对应的路由组件
]

new Router({
routes
})
```
4. 在根实例里注入router,目的是为了让所有的组件里都能通过this.$router来使用路由的相关功能api
```
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
```
5. 利用router-view来指定路由切换的位置

6. 使用router-link来创建切换的工具,会渲染成a标签,添加to属性来设置要更改的path信息,且会根据当前路由的变化为a标签添加对应的router-link-active类名
```
<router-link to="main">main</router-link>
<router-link to="news">news</router-link>
.router-link-active{
color:red;
}
```

原文地址:https://www.cnblogs.com/swiftlai/p/8098810.html