vue.js---路由vue-router

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011649691/article/details/81977735

代码在gitbub:https://github.com/icarusion/vue-book
1、安装vue-router依赖,添加到dependences中

npm install --save vue-router

2、在main.js中使用Vue.use()加载插件:

import VueRouter from 'vue-router';
Vue.use(VueRouter);

3、每个页面对应一个组件,也就是对应一个.vue文件。在router目录下创建views目录,用于存放所有的页面,然后在views里创建index.vue和about.vue两个文件:

//index.vue
<template>
    <div>
        <h1>首页</h1>
        <router-link to="/about">跳转到 about</router-link>
    </div>
</template>
<script>
    export default {

    }
</script>
//about.vue
<template>
    <div>
        <h1>介绍页</h1>
        <button @click="handleRouter">跳转到 user</button>
    </div>
</template>
<script>
    export default {
        methods: {
            handleRouter () {
                this.$router.push('/user/123');
            }
        }
    }
</script>
//user.vue
<template>
    <div>{{ $route.params.id }}</div>
</template>
<script>
    export default {
        mounted () {
            console.log(this.$route);
        }
    }
</script>

4、在main.js中,完成路由的剩余配置,创建一个数组来制定路由匹配列表,每个路由映射一个组件:

// 路由配置
const Routers = [
    {
        path: '/index',
        meta: {
            title: '首页'
        },
        component: (resolve) => require(['./views/index.vue'], resolve)
    },
    {
        path: '/about',
        meta: {
            title: '关于'
        },
        component: (resolve) => require(['./views/about.vue'], resolve)
    },
    {
        path: '/user/:id',
        meta: {
            title: '个人主页'
        },
        component: (resolve) => require(['./views/user.vue'], resolve)
    },
    {
        path: '*',
        redirect: '/index'
    }
];

上例中实现的懒加载,Routers里每一项的path属性就是制定当前匹配的路径,component是映射的组件。上例的写法,webpack会把每一个路由都打包为一个js文件,在请求到该页面时,才去加载这个页面的js。这样做的好处是不需要在打开首页的时候就把所有的页面内容加载进来,只在访问时才加载。如果非要一次性加载,可以这样写:

{
    path:'/index',
    component:require('./views/index.vue')
}

5、设置路由模式和路由实例:

const RouterConfig = {
    // 使用 HTML5 的 History 路由模式
    mode: 'history',
    routes: Routers
};
const router = new VueRouter(RouterConfig);

new Vue({
    el: '#app',
    router: router,
    render: h => {
        return h(App)
    }
});

在routerconfig中,设置使用了html5的history路由模式,通过‘/’设置路径。如果不配置mode,就会使用’#’来设置路径。开启History路由,在生成环境时服务器端必须进行配置,将所有路由指向同一个html,或者设置404页面为该html。否则刷新时页面会出现404.
另外webpack-dev-server也要配置来支持history路由,在package.json中修改dev命令:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --open --history-api-fallback --config webpack.config.js",
    "build": "webpack --progress --hide-modules --config webpack.prod.config.js"
  },
  增加了--history-api-fallback,所有的路由都会指向index.html

6、在根实例app.vue中添加一个路由视图<router-view>来挂载所有的路由组件:

<template>
    <div>
        <router-view></router-view>
    </div>
</template>
<script>
    export default {

    }
</script>

7、跳转规则的设置
vue-router有2种跳转页面的方法。
第一种是使用内置的<router-link>组件,它会被渲染为一个<a>标签:

//index.vue
<template>
    <div>
        <h1>首页</h1>
        <router-link to="/about">跳转到 about</router-link>
    </div>
</template>

<router-link>中常用的prop,在html5的history模式下会拦截点击,避免浏览器重新加载页面:
to:指定需要跳转的路径,也可以使用v-bind动态设置。
tag:可以指定渲染成什么标签,比如<router-link to="/about" tag="li">,那么就可以渲染成li而不是a
replace:使用replace不会留下history记录,所以导航后不能用后退键返回上一个页面,如<router-link to="/ablout" replace>

第二种是使用javascript,类似于window.location.href。比如在上例中的about.vue中就是使用的这种方法。
$router还有其他一些方法:
replace:类似于<router-link>的replace功能。它不会向history添加新记录,而是替换掉当前的history记录,this.$router.replace('/user/123')
go:类似于window.history.go(),在history记录中向前或者向后退多少步,参数是整数。this.$router.go(-1)后退1步;this.$router.go(2)前进2步。
8、高级功能,导航钩子beforeEach,afterEach,它们会在路由即将改变前和改变后触发,这2个钩子都有3个参数:to,from,next。
to:即将要进入的目标的路由对象
from:当前导航即将要离开的路由对象
next:调用该方法后,才能进入下一个钩子。
例如:

//打开新的页面前,改变浏览器页面标题
router.beforeEach((to, from, next) => {
    window.document.title = to.meta.title;
    next();
});
//打开新的页面后,滚动条回到顶端
router.afterEach((to, from, next) => {
    window.scrollTo(0, 0);
});

猜你喜欢

转载自blog.csdn.net/u011649691/article/details/81977735
今日推荐