main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
Vue.config.productionTip = false
Vue.use(VueRouter)
const Routers = [
{
path:'/index',
component:(resolve)=>require(['./views/index.vue'], resolve),
},
{
path:'/about',
component:(resolve)=>require(['./views/about.vue'], resolve),
},
{
path:'/users/:id',
component:(resolve)=>require(['./views/users.vue'], resolve),
},
{
path:'*',
redirect:'/index',
},
]
const RouterConfig = {
mode:'history',//history or hash
routes:Routers
}
const router = new VueRouter(RouterConfig)
new Vue({
router: router,
render: h => h(App),
}).$mount('#app')
App.vue
<template>
<div id="app">
<router-link to="/index" tag="li">Go to index</router-link>
<router-link to="/about" tag="li">Go to about</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'app',
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
-
<router-link to="/index" tag="li">Go to index</router-link>
的tag
可以定义跳转类型,默认为a标签; -
<router-link>
加上replace
会使得浏览器后退没有历史记录,返回最开始页面 -
<router-link>
加上active-class='light-class'
并自定义light-class
可以使得链接附加高亮等功能 - 编程式导航,通过js跳转
methods:{
toLink(){
this.$router.push('/users/12')
//this.$router.replace('/users/12')
//this.$router.go(-1)
}
}
高级用法
- 设置标题
router.beforeEach((to,from,next)=>{
window.document.title = to.meta.title
next()
})
next()不填参数默认继续跳到预跳页面(to页面)
next('/index')填参数可以修改跳转页面
next(False)不跳转
- 返回顶端
router.afterEach((to,from,next)=>{
window.scrollTo(0,0)
})
网友评论