vue-router的一些使用方法

2018-03-22  本文已影响0人  十年之后_b94a

1)基本使用

路由是什么
例如:www.baidu.com 这个路由就是'/'
如果www.baidu.com/all 这个路由就是'/all'
//路由的定义

import Vue from 'vue'
import Router from 'vue-router'
import elGoods from './goods/goods' //商品tab
import elRatings from './ratings/ratings' //评论tab
import elSeller from './seller/seller' //商家tab
Vue.use(Router)

export default new Router({
  mode:"history",
  routes: [
    {
        path: '/', 
        redirect: 'goods' //重定向路由
    },
    { //商品tab
      path: '/goods',
      name: 'elGoods',
      component: elGoods //这个路由需要展示的内容组成组件
    },
    { //评论tab
      path: '/ratings',
      name: 'elRatings',
      component: elRatings
    },
    { //商家tab
      path: '/seller',
      name: 'elSeller',
      component: elSeller
    }
  ]
})

如果在一整个页面开发中
根节点只有一个#app
那么整个页面都会被路由替换

<div id="app">
  <router-view></router-view>
</div>

而如果页面头部一致

<div id="app">
  <...>
    这里可以直接写头部代码,或者引用头部组件
  例如
  <my-header></my-header>
  <...>
  <router-view></router-view>
</div>

2)路由模式history与常规模式

首先介绍常规模式
就上诉中www.***.com/#/index
那么这个#/index就是常规模式,也就是所说的hash路由
不需要配置什么前端与后端都不需要,因为vue是单页面应用

那么什么是history模式呢
www.****.com/index
www.****.com/login
这个是不是很常见这个就是history模式了,但是因为vue是单页面应用这个需要后端同学来配置了

//前端配置路由的时候加上history 注意常规路由(hash路由)不需要天假mode属性
export default new Router({
  mode:"history",
  routes: [
    {
        path: '/', 
        redirect: 'goods' //重定向路由
    },
    { //商品tab
      path: '/goods',
      name: 'elGoods',
      component: elGoods //这个路由需要展示的内容组成组件
    },
    { //评论tab
      path: '/ratings',
      name: 'elRatings',
      component: elRatings
    },
    { //商家tab
      path: '/seller',
      name: 'elSeller',
      component: elSeller
    }
  ]
})

但是对于history路由来说 打包上线之后就会出现404了,因为后端中配置的接口模式/asd/asdasd就会匹配例如
www.****.com/asd/asdasd 那么就可能会冲突,甚至会导致404
那么后端的同学需要,所有的get请求404转发的index或者/路由去,因为vue是单页面,始终是一个页面做切换

上一篇 下一篇

猜你喜欢

热点阅读