vue-router

86 阅读1分钟

mode: 'history' linkActiveClass: 'active'

方法定义跳转

methods:{
    homeClick(){
        this.$router.push('/home')
        this.$router.replace('/home')

        //所有的组件都继承自Vue类的原型
        console.log(this.$router)
        console.log(this.$route)
    }
}

vueRouter对象

{
    path: '',
    //redirect 重定向
    redirect: '/home'
},{
    path: '/home',
    component: Home
},{
    path: '/user/:abc',
    component: User
}

router-link 补充

tag: tag 可以指定<router-link> 之后渲染成什么组件,比如上面的代码会被渲染成一个<li>元素,而不是<a>

replace: replace 不会留下history 记录,所以指定replace的情况下,后退键返回不能返回到上一个页面中

active-class: 当<router-link> 对应的路由匹配成功时,会自动给当前元素设置一个router-link-activeclass, 设置active-class可以修改默认的名称

动态路由

  • router文件下index.js
data(){
    return {
        userId: 'Id1'
    }
}
  • App.vue
<router-link :to="'/user/' + userId">用户</router-link>
  • User.vue
<h2>{{$router.params.abc}}</h2>

computed: {
    userId() {
        //$route 当前哪个路由处于活跃状态就是哪个
        //params 当前用户,参数
        return this.$route.params.abc
        
    }
}

路由的懒加载(用到时,再加载)

一个路由打包一个js文件

const Home = () => import('../components/Home')
const About = () => import('../components/About')
const User = () => import('../components/User')

嵌套路由

const HomeNews = () => import('../components/HomeNews')
{
    path: '/home',
    component: Home
    children: [
        {   //默认显示
            path: '',
            redirect: 'news'
        },
        {
            path: 'news',
            component: HomeNews
        }
    ]
}

// 对应位置
<router-link :to="/home/news">新闻</router-link>
<router-view></router-view>

路由传递参数

第一种上面的

/router/:id
this.$route.params.abc

第二种

<router-link :to="{path: '/profile', query: {name: 'aa', age: 18}}">档案</router-link>

如果不用router-link 改用button

<button @click="userClick">用户</button>
<button @click="profileClick">档案</button>

methods:{
    userClick() {
        this.$router.push('/user/' + this.userId)
    }
    profileClick() {
        this.$router.push({
            path: '/profile',
            query: {
                name: 'aa',
                age: 18                  
            }
        })
    }
}

routerrouter 和 route 的区别

routerVueRouter实例,想要导航到不同的URL,则使用router 为 VueRouter实例,想要导航到不同的URL,则使用 router.push方法 $route 为当前 router 跳转对象里面可以获取name,path,query,params等

路由 全局导航守卫-网页标题

created 创建的时候回调 mounted template 挂在到vdom 的时候回调 updated 界面发生刷新时回调

全局守卫

前置钩子(hook), 跳转之前进行回调

router.beforeEach(to, from, next) => {
    // 从from 跳转到 to
    document.title = to.matched[0].meta.title
    next()
}
// 后置钩子(hook)
router.afterEach(to, from) => {
}

还有路由独享的守卫 组件内的守卫

// meta 元数据

meta: {
    title: '首页'
}

keep-alive

beforeEach() {
}