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






  • Go to indextag可以定义跳转类型,默认为a标签;
  • 加上replace会使得浏览器后退没有历史记录,返回最开始页面
  • 加上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)
})

你可能感兴趣的:(vue-router)