路由 Vue Router

对于单页面应用来说,如果涉及到多个页面的话,就必须要使用到路由,一般使用官方支持的 vue-router

一,Vue Router 在项目中的安装引用

1,在页面中使用<script>快速使用Vue Router开发

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>使用script直接引入Vue Router</title>
</head>
<body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<h1>页面共同header</h1>
<p>
<router-link to="/first">页面1</router-link>
<router-link to="/second">页面2</router-link>
</p>
<router-view></router-view>
</div>
<script> //template也可以使用import从外部引入进来
const first = { template: '<div>I am first</div>' }
const second = { template: '<div>I am second</div>' }
const routes = [
{ path: '/first', component: first },
{ path: '/second', component: second }
]
const router = new VueRouter({
routes
})
const app = new Vue({
router
}).$mount('#app')
</script>
</body>
</html>

2,在vue cli框架使用路由

app.js

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

main.js

import Vue from "vue";
import App from "./App.vue";
import router from "./router.js";
Vue.config.productionTip = false; new Vue({
router,
render: h => h(App)
}).$mount("#app");

router.js

import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const routes = [
{
path: '/index',
name: 'index',
component: () => import("@/views/index.vue"),
},
{
path: '/login',
name: 'login',
component: () => import("@/views/login.vue"),
},
{
path: '/fansNumber',
name: 'fansNumber',
component: () => import("@/views/fansNumber.vue"),
}
]; routes.forEach(route => {
route.path = route.path || '/' + (route.name || '');
});
const router = new Router({ routes });
router.beforeEach((to, from, next) => {
//路由执行之前,处理一些逻辑
next();
})
export default router;

 二,Vue Router 基础功能用法

1,router-路径式传参

//路由定义 router.js
const router = new VueRouter({
routes: [
// 动态路径参数 以冒号开头
{ path: '/user/:id', component: User }
]
}) //第一种编程式跳转指定路由 test.vue
const userId = '123'
this.$router.push({
path: '/user/' + userId
})
//第二种编程式跳转指定路由 test.vue
this.$router.push({
name: 'user',
params: userId
})
//声明式跳转指定路由 test.vue
<router-link to="/user/{{userId}}">
<span>跳转</span>
</router-link> //在user的js里面接收参数
created() {
console.info(this.$route.params.userId)
}

注:你可以在一个路由中设置多段『路径参数』,对应的值都会设置到 $route.params 中。例如:

模式 匹配路径 $route.params
/user/:username /user/jack { username:'jack' }
/user/:username/pwd:password /user/jack/pwd/123 { username:'jack',pwd:123

2,router-get方式传参

//路由定义 router.js
const router = new VueRouter({
routes: [
{ path: '/user', component: User }
]
}) //编程式跳转到指定路由 test.vue
this.$router.push({
name: "user",
query: {
userName: 'jack'
pwd: '123'
}
});
//在user的js里面接收参数
created() {
console.info(this.$router.query.userName)
console.info(this.$router.query.pwd)
}

3,编程式导航

  • router.replace() 和 router.push() 一样的用法,区别为:
  • router.push() 每次调用,都会往history里面添加一条新纪录,可以返回历史页面
  • router.replace() 每次调用,不会往history里面添加记录,而是会替换掉当前的history记录,没有历史记录
  • router.go(1)  //浏览器中,向前进一步,等同于history.foward()
  • router.go(-1) //浏览器中,向后一步,等同于history.back()

4,基于路由的动态过渡效果

<template>
<div id="app">
<transition name="fade">
<router-view></router-view>
</transition>
</div>
</template>
<style lang="scss">
.fade-enter-active{
transition: opacity .6s;
}
.fade-enter{
opacity: .5;
}</style>

5,导航守卫,过滤器

const router = new VueRouter({
routes: [
{
path: "/home",
name: "Home",
component: Home,
meta: {
type: '1',
title: '首页'
}
}
]
}); //路由执行前
router.beforeEach((to, from, next) => {
//校验token是否过期
if(to.token && Util.checkToken(to.token)){
return next({path: to.path});
}else{
return next({path: '/login'});
}
//使用路由自定义meta,统一处理title
const title = to.meta && to.meta.title;
if (title) {
document.title = title;
}
})
//路由执行后
router.afterEach((to) => {
//恢复页面滚动位置
window.scrollTo(0, 0);
}); export default router;

6,使用scrollBehavior中的异步滚动

const router = new Router({
scrollBehavior(to, from, savedPosition) {
// keep-alive 返回缓存页面后记录浏览位置
if (savedPosition && to.meta.keepAlive) {
return savedPosition;
}
// 异步滚动操作
return new Promise((resolve) => {
setTimeout(() => {
resolve({ x: 0, y: 1 });
}, 0);
});
},
});

更多功能,请参考router官网

Vue技术点整理-Vue Router的更多相关文章

  1. Vue技术点整理-Vue CLI

    Vue CLI 是一个基于 Vue.js 进行项目快速开发的脚手架 注:具体安装步骤可参考Vue CLI,默认安装的脚手架,是没有service.util等工具类的,以下主要描述如何在脚手架的基础上进 ...

  2. Vue技术点整理-Vue CLI安装详解

     一,脚手架安装 Node 版本要求 Vue CLI 需要 Node.js +).你可以使用 nvm 或 nvm-windows 在同一台电脑中管理多个 Node 版本. 1,全局安装Vue CLI ...

  3. Vue技术点整理-vue.config.js

    1,proxy代理解决本地开发环境跨域问题 配置proxy代理后,proxy会将任何未知请求 (没有匹配到静态文件的请求) 代理到 https://192.168.3.49:8080 vue.conf ...

  4. Vue技术点整理-前言

    前言 Vue版本说明:本文档编写时,Vue稳定版本为 2.6.10 本文档编写目的为:整理Vue相关生态的技术点.和开发中经常使用到的技术点,让开发者快速上手开发,提升开发效率 一,Vue开发工具:本 ...

  5. Vue技术点整理-安装引入

    Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架 所谓渐进式是指: 1,如果你有一个现成的web应用,你可以将vue作为该应用的一部分嵌入其中,带来更丰富的交互体验 ...

  6. Vue技术点整理-Vuex

    什么是Vuex? 1,Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化 2,每一个 Vuex ...

  7. Vue技术点整理 vue-devtools

    注:默认浏览器调试工具,在调试vue的页面时,是不能看到vue项目的属性状态值的,所以最好是在浏览器上安装 vue-devtools,这样就可以在浏览器里面审查和调试vue的应用了 1,Chrome浏 ...

  8. Vue技术点整理-指令

    我们通常给一个元素添加 v-if / v-show 来做权限管理,但如果判断条件繁琐且多个地方需要判断,这种方式的代码不仅不优雅而且冗余. 针对这种情况,我们可以通过全局自定义指令来处理:我们先在新建 ...

  9. php开发面试题---jquery和vue对比(整理)

    php开发面试题---jquery和vue对比(整理) 一.总结 一句话总结: jquery的本质是更方便的选取和操作DOM对象,vue的本质是数据和页面分离 反思的回顾非常有用,因为决定了我的方向和 ...

随机推荐

  1. asp .net Cookies

    Request.Cookies和Response.Cookies When validating cookies or cookie data from the browser you should ...

  2. PostSharp-5.0.26安装包_KeyGen发布_支持VS2017

    PostSharp-5.0.26安装包_KeyGen发布_支持VS2017 请低调使用. PostSharp安装及注册步骤截图.rar 请把浏览器主页设置为以下地址支持本人.https://www.d ...

  3. WPF ObjectDataProvider的使用-只能检索用

    <Window x:Class="CollectionBinding.MainWindow"        xmlns="http://schemas.micros ...

  4. C语言反汇编入门实例

    看<天书夜读>第一章,感觉很亲切,于是自己动手操起VS,建立一个默认的Win32 Console Application,在一个空空的main函数里面F9下一个断点之后,按下F5进入调试, ...

  5. 怎样解决python dataframe loc,iloc循环处理速度很慢的问题

    怎样解决python dataframe loc,iloc循环处理速度很慢的问题 1.问题说明 最近用DataFrame做大数据 处理,发现处理速度特别慢,追究原因,发现是循环处理时,loc,iloc ...

  6. .Net 通过Cmd执行Adb命令 /c参数

    通过cmd.exe来执行adb命令,可以进行一些命令组合,直接用adb.exe的话只能执行单个adb命令 这里要注意cmd 中的/c参数,指明此参数时,他将执行整个字符串中包含的命令并退出当前cmd运 ...

  7. asp.net 调用带证书的webservice解决办法

    最近在朋友弄一个调整省政府政务工作流的程序.. 需要把当前的信息推送到政务网上,采用的是带证书的https webservice.. 下面说一下实现过程 第一步,引用webservice地址,删除we ...

  8. tf.nn.softmax & tf.nn.reduce_sum & tf.nn.softmax_cross_entropy_with_logits

    tf.nn.softmax softmax是神经网络的最后一层将实数空间映射到概率空间的常用方法,公式如下: \[ softmax(x)_i=\frac{exp(x_i)}{\sum_jexp(x_j ...

  9. Change Default Route

    route delete 0.0.0.0route add 0.0.0.0 mask 0.0.0.0 10.226.4.14

  10. 如何设计出和 ASP.NET Core 中 Middleware 一样的 API 方法?

    由于笔者时间有限,无法写更多的说明文本,且主要是自己用来记录学习点滴,请谅解,下面直接贴代码了(代码中有一些说明): 01-不好的设计 代码: using System; namespace Desi ...