vue-router

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)
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容