Vue-Router的使用(一)

1.首先,安装vue-router

npm install vue-router --save-dev

2.创建一个route.js文件

// 1. 定义路由组件
// 可以自己写的,或者导入的,大部分是导入的
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

// 2. 定义路由规则
// 每个路由映射一个组件
const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

//导出使用 export default=routes;

路由懒加载

作用:当路由被访问的时候才加载对应组件

适用范围:当构建的项目比较大的时候,懒加载可以分割代码块,提高页面的初始加载效率。

第一种写法

const routers = [ { path: '/', name: 'index', component: (resolve) => require(['./views/index.vue'], resolve) } ]

 第二种写法 

const Index = () => import(/* webpackChunkName: "group-home" */  '@/views/index')
const routers = [
    {
        path: '/',
        name: 'index',
        component: Index
    }
]

 第三种

const Index = r => require.ensure([], () => r(require('./views/index')), 'group-home');
const routers = [
    {
        path: '/',
        name: 'index',
        component: Index
    }
]

  其中‘group-home’ 是把组件按组分块打包, 可以将多个组件放入这个组中

3.在入口文件中进行路由的使用

import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from "./Admin/route/route.js";//导入路由文件
//使用插件
Vue.use(VueRouter)
//实例化
const router = new VueRouter({
    routes,
    mode: 'history'
})
//使用
new Vue({
    el: '#app',
    template: "<div><router-view></router-view></div>",
    router
})

  

4.在组件文件中的使用,获取参数,跳转等操作  

// Home.vue
<template>
<div id="app">
  <h1>Hello App!</h1>
  <p>
    <!-- use router-link component for navigation. -->
    <!-- specify the link by passing the `to` prop. -->
    <!-- `<router-link>` will be rendered as an `<a>` tag by default -->
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <!-- route outlet -->
  <!-- component matched by the route will render here -->
  <router-view></router-view>
</div>
</template>
<script> export default { computed: { username () { // We will see what `params` is shortly return this.$route.params.username } }, methods: { goBack () { window.history.length > 1 ? this.$router.go(-1) : this.$router.push('/') } } }
</script>

 5.路由方法Api

router.push(location, onComplete?, onAbort?)
例子:
const userId = 123
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// This will NOT work
router.push({ path: '/user', params: { userId }}) // -> /user

router.go(n)
例子:
   // go forward by one record, the same as history.forward()
router.go(1)

// go back by one record, the same as history.back()
router.go(-1)

  

  

posted @ 2018-06-19 16:50  FeelRose  阅读(324)  评论(0编辑  收藏  举报