1.安装 npm install vue-router
(也可直接在创建vue项目中时,安装好)
2.main.js中(全局)进行引入,同时需要在new Vue中加入router
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/>'
})
3.若是直接在创建vue项目时选择安装了vue-router,只需在router/index.js中逐个添加每个路由即可,后续安装vue-router,需要自己手动添加router的文件夹,底下创建index.js文件。然后在main.js中引入router文件。
若在一个模块化工程中使用到vue-router,必须通过Vue.use()明确的安装路由功能。
其中的name值主要用于传递参数时,所需用到的路由name值。
index.js
import Vue from 'vue'
import Router from 'vue-router'
import index from '../components/index'
Vue.use(Router)
export default new Router({
linkActiveClass:"active",
routes: [
{
path: '/',
name: 'index',
component: index
}
]
})
视图加载
<router-view></router-view>
路由跳转,相当于a标签,其中的to属性,指定需跳转的路由路径。
<ul>
<li><router-link to="/" exact>index</router-link></li>
<li><router-link to="/hello">hello</router-link></li>
</ul>
页面不用a标签的好处:
1.无论是HTML5 history模式还是hash,他的表现行为一致,当需切换路由,不需要作任何变动。
2.浏览器不需要重新加载页面。
3.在HTML5 history下使用base,所有的to都不需要写基路径。
网友评论