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可以定義跳轉(zhuǎn)類(lèi)型,默認(rèn)為a標(biāo)簽; -
<router-link>加上replace會(huì)使得瀏覽器后退沒(méi)有歷史記錄,返回最開(kāi)始頁(yè)面 -
<router-link>加上active-class='light-class'并自定義light-class可以使得鏈接附加高亮等功能 - 編程式導(dǎo)航,通過(guò)js跳轉(zhuǎn)
methods:{
toLink(){
this.$router.push('/users/12')
//this.$router.replace('/users/12')
//this.$router.go(-1)
}
}
高級(jí)用法
- 設(shè)置標(biāo)題
router.beforeEach((to,from,next)=>{
window.document.title = to.meta.title
next()
})
next()不填參數(shù)默認(rèn)繼續(xù)跳到預(yù)跳頁(yè)面(to頁(yè)面)
next('/index')填參數(shù)可以修改跳轉(zhuǎn)頁(yè)面
next(False)不跳轉(zhuǎn)
- 返回頂端
router.afterEach((to,from,next)=>{
window.scrollTo(0,0)
})