路由内容概述
1.什么是路由?
路由(routing)就是通过互联的网络把信息从源地址传输到目的地址的活动.
路由器提供了两种机制: 路由和转送.
路由是决定数据包从来源到目的地的路径.
转送将输入端的数据转移到合适的输出端.
路由中有一个非常重要的概念叫路由表.
路由表本质上就是一个映射表, 决定了数据包的指向.
2.vue-router路由规则
路由有俩种模式 mode:'hash'/'history'
3 安装和使用vue-router
步骤一: 安装vue-router
npm install vue-router --save
步骤二: 在模块中使用vue-router插件
创建一个index.js文件,里面写
1.导入路由对象,并调用
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter); //调用
2.配置路由映射
const routes= [
{
path: '',
redirect: '/home' //重定向
},
{
path: '/Home',
component: Home
},
{
path: '/category',
component: Cart
},
{
path: '/profile',
component: Profile
},
{
path: '/detail/:iid',
component: Detail
}
];
3.创建路由实例并导出路由,然后在main.js的vue实例中挂载
//创建vueRouter实例
var router = new VueRouter({
routes,
mode: 'history' //模式为history 还有hash #/
})
//导出
export default router
4.使用路由
使用路由: 通过<router-link>和<router-view>
******下面通过图来解释一下这几个步骤*********
创建路由实例
挂载路由实例(在main.js中挂载)
改变路径的方式:
1.url中的hash
2.HTML5的history(默认路径的改变使用的URL的hash)
完整配置路由代码
import Vue from 'vue';
import VueRouter from 'vue-router';
//懒加载
const Home = () => import('../views/home/Home');
const Category = () => import('../views/category/Category');
const Cart = () => import('../views/cart/Cart');
const Profile = () => import('../views/profile/Profile');
const Detail = () => import('../views/detail/Detail');
//1.安装插件
Vue.use(VueRouter);
//2.创建router
const routes= [
{
path: '',
redirect: '/home' //重定向
},
{
path: '/Home',
component: Home
},
{
path: '/category',
component: Cart
},
{
path: '/profile',
component: Profile
},
{
path: '/detail/:iid',
component: Detail
}
];
//路由导航守卫
// router.beforeEach(to,from,next){}
// router.afterEach(to,from,next){}
//创建vueRouter实例
var router = new VueRouter({
routes,
mode: 'history' //模式为history 还有hash #/
})
//导出
export default router