vue路由,路由传参(parmas,query)

本文详细介绍了Vue Router的基础用法、路由配置的抽取、动态传值、编程式导航、不同模式(hash与history)、路由嵌套以及登录与首页的路由配置。重点讲解了如何在Vue应用中设置和管理路由,包括路由的跳转方式、参数传递以及路由模式的切换。此外,还对比了hash模式和history模式的差异,并展示了实际应用场景。
摘要由CSDN通过智能技术生成

一、Vue路由基础用法:

1 .安装
 npm install vue-router --save
2 .main.js中
//Vue路由:引入
import VueRouter from 'vue-router'
Vue.use(VueRouter)

//Vue路由:引入并创建组件
import BYHome from './components/BYHome.vue'
import BYNews from './components/BYNews.vue'
import HelloWorld from './components/HelloWorld.vue'

//Vue路由:配置路由
const routes = [
  {path: '/home', component: BYHome},
  {path: '/news', component: BYNews},
  {path: '/helloworld', component: HelloWorld},
  {path: '*', redirect: '/home'} /*默认跳转路由 */
]

//Vue路由:实例化VueRouter 
const router = new VueRouter({
  routes //缩写,相当于 routes:routes
})

new Vue({
  router, //Vue路由:挂载路由
  render: h => h(App),
}).$mount('#app')

//Vue路由:根组件的模板里面放上下面这句话,需要在App.vue 中配置路由出口:路由匹配到的组件将渲染在根组件App.vue中
<router-view></router-view>

//路由跳转
<router-link to="/home">首页</router-link>  
<router-link to="/news">新闻</router-link>
<router-link to="/helloworld">helloWorld</router-link>

二、Vue路由配置的抽出

1.安装

  npm install vue-router --save

2.创建router.js文件,在该文件中配置路由并暴露出去

 import Vue from 'vue';
  //Vue路由:引入
    import VueRouter from 'vue-router'
    Vue.use(VueRouter)

    //Vue路由:引入并创建组件
    import BYHome from '../BYHome.vue'
    import BYNews from '../BYNews.vue'
    import HelloWorld from '../HelloWorld.vue'

    //Vue路由:配置路由
    const routes = [
      {path: '/home', component: BYHome},
      {path: '/news', component: BYNews},
      {path: '/helloworld', component: HelloWorld},
      {path: '*', redirect: '/home'} /*默认跳转路由 */
    ]

    //Vue路由:实例化VueRouter 
    const router = new VueRouter({
      routes //缩写,相当于 routes:routes
    })
    //Vue路由:需要在App.vue 中配置路由出口:路由匹配到的组件将渲染在根组件App.vue中
    /* <router-view></router-view> */


    //暴露出去
    export default router;

3.在main.js中

//Vue路由:引入路由文件
import router from ‘./components/jsTool/router.js’

new Vue({undefined
router, //Vue路由:挂载路由
render: h => h(App),
}).$mount(’#app’)

4.Vue路由:根组件的模板里面放上下面这句话,需要在App.vue 中配置路由出口:路由匹配到的组件将渲染在根组件App.vue中

   <router-view></router-view>

5.路由跳转

<router-link to="/home">首页</router-link>  
<router-link to="/news">新闻</router-link>
  <router-link to="/helloworld">helloWorld</router-link>

三、路由动态传值:

1.获取路由的get传值

//路由配置

import BYHomeDetail from '../BYHomeDetail.vue'
{path: '/homeDetail', component:BYHomeDetail},
//跳转时跟get参数
<li li v-for="(listItem,homeKey) in msglist">
            <router-link :to="'/homeDetail?id='+homeKey"> {{listItem.title}} </router-link>
 </li>
 //子页面获取路由的get传值
  mounted(){
    console.log(this.$route.query);
}

2.动态路由传值

//路由配置:带形参
import BYNewDetail from '../BYNewDetail.vue'
{path: '/newDetail/:aid', component: BYNewDetail}, 
//跳转时传值
<li v-for="(item,key) in list">
    <!-- 给 newDetail 传值 -->
    <router-link :to="'/newDetail/'+key">{{key}}--{{item}}</router-link>
</li>
//子页面获取动态路由传值
 mounted(){
    console.log(this.$route.params);
}

四、路由的跳转方式:

第一种跳转方式:编程式导航

{path: '/news', component: BYNews},
this.$router.push({path:'news'});
带参:
{path: '/newDetail/:aid', component: BYNewDetail},
this.$router.push({path:'/newDetail/495'});

第二种跳转方式:命名路由

 {path: '/news', component: BYNews,name:'news'},
    this.$router.push({name:'news'});
    带参:
    this.$router.push({name:'news',params:{userId:123}});

五、路由的hash模式以及history模式:

默认是hash模式,路由上方的路径是用#表示,http://localhost:8080/#/news

可以将hash模式改为history模式,路由上方的路径就没有了

#,http://localhost:8080/news 
  如果有history模式,需要后台做一些配置
  //Vue路由:实例化VueRouter 
const router = new VueRouter({
  mode: 'history',   //若是默认的hash模式,则mode不需要写
  routes //缩写,相当于 routes:routes
})

六、路由的嵌套

User.vue页面中有两个子页面
UserAdd.vue
UserList.vue

//路由的配置
import BYUser from '../BYUser.vue'
  import UserAdd from '../User/UserAdd.vue'
  import UserList from '../User/UserList.vue'

{path: '/user' , component:BYUser,
    children:[
      {path: 'useradd',component:UserAdd},
      {path: 'userlist',component:UserList}
    ]
},

//路由的跳转
<div>
    <div class="left">
        <ul>
            <li>
                <router-link to="/user/useradd"> 增加用户 </router-link>
            </li>
            <li>
                 <router-link to="/user/userlist"> 用户列表 </router-link>
            </li>
        </ul>
    </div>
    <div class="right">
        <router-view></router-view>
    </div>
</div>

七、登录及首页的路由配置说明
1.创建一个localstorage本地存储类storage.js,用来记录登录状态

var storage={
    set(key,value){
        console.log("storage---->")
        console.log(value)
        localStorage.setItem(key, JSON.stringify(value));
    },
    get(key){
        return JSON.parse(localStorage.getItem(key));
    },remove(key){
        localStorage.removeItem(key);
    }
}
export default storage;

2.创建一个自定义的路由表:router.js

import Vue from 'vue';
//引入路由
import VueRouter from 'vue-router'
Vue.use(VueRouter)

//设置路由表
const routes = [
 {
   path: '/',
   redirect: '/home'
 },
 {path: '/404', component: resolve => require(['../common/404.vue'],resolve)},
 {path: '/login', component: resolve => require(['../page/Login.vue'],resolve)},
 {path: '/home',component: resolve => require(['../page/Home.vue'],resolve),meta:{requireAuth:true}},//加上meta 表示需要登录才可进入
 {
   path:'*',
   redirect:'/404'
 }
]
//实例化路由并指定模式
const router = new VueRouter({
 /*默认是hash模式,路由上方的路径是用#表示,http://localhost:8080/#/news
 可以将hash模式改为history模式,路由上方的路径就没有了#,http://localhost:8080/news 
   如果有history模式,需要后台做一些配置
 */
   // mode:'history',
   routes //缩写,相当于 routes:routes
})
//暴露出去,供外部调用
export default router;

3.在main.js中配置钩子路由:

//引入自定义的路由表
import router from './components/router/router.js'
//引入localstorage本地存储管理
import storage from "./components/Tools/storage.js";
/**在路由跳转之前执行
 * to: 即将进入的路由对象
 * from: 当前导航即将离开的路由
 * next:Function,进行管道中的一个钩子,如果执行完了,则导航的状态就是 confirmed (确认的);否则为false,终止导航。
 *  */
router.beforeEach((to, from, next) => { 
  //需要登录,但未登录者可以跳转到登录页面
  const isLogin = storage.get('login');
  if(!isLogin && to.meta.requireAuth){//未登录 且 需要登录(提前在路由表中加上meta)
    next({
      path:'/login'
    })
  }else{//其他
    next();
  }
});

4.登录及退出登录

    
登录:
    console.log("登录成功");
    let flag = true;
    storage.set('login',flag);//存储登录状态
    this.$router.push('/');//按路由规则跳转
退出登录:
    console.log("退出登录");
    let flag = false;
    storage.set('login',flag);//存储登录状态
    this.$router.push('/login');//按路由规则跳转
            

vue-Router实现原理

一、前端路由概念
通过改变 URL,在不重新请求页面的情况下,更新页面视图。

二、vue-Router两种模式
更新视图但不重新请求页面,是前端路由原理的核心之一,目前在浏览器环境中这一功能的实现主要有2种方式:

Hash — 默认值,利用 URL 中的hash("#") 、

history-- 利用URL中的路径(/home)

如何设置路由模式
 

const router=new VueRouter({
    mode:'history',
    routes:[...]
})

mode 区别:

  1. mode:“hash” 多了 “#”
http://localhost:8080/#/login
  1. mode:“history”
    http://localhost:8080/home
    

    三、HashHistory
    hash("#")的作用是加载 URL 中指示网页中的位置。# 号后面的 hash值,可通过 window.location.hash 获取

    特点:

    hash 不会被包括在 http 请求中,,对服务器端完全无用,因此,改变 hash 不会重新加载页面。

    可以为 hash 的改变添加监听事件:window.addEventListener("hashchange",funcRef,false)

    每一次改变 hash(window.localtion.hash),都会在浏览器访问历史中增加一个记录。

    利用 hash 的以上特点,就可以来实现前端路由"更新视图但不重新请求页面"的功能了。

    HashHistory 拥有两个方法,一个是 push, 一个是 replace

    两个方法:HashHistory.push() 和 HashHistory.replace()
    1
    HashHistory.push() 将新路由添加到浏览器访问历史的栈顶

    在这里插入图片描述


    从设置路由改变到视图更新的流程:

    $router.push() --> HashHistory.push() -->History.transitionTo() --> History.updateRoute() --> {app._route = route} --> vm.render()

    解释:

    $router.push() //调用方法
    HashHistory.push()//根据hash模式调用,设置hash并添加到浏览器历史记录(添加到栈顶)(window.location.hash= XXX)
    History.transitionTo() //监测更新,更新则调用History.updateRoute()
    History.updateRoute() //更新路由
    {app._route= route} //替换当前app路由
    vm.render() //更新视图

    HashHistory.replace()

    replace()方法与push()方法不同之处在于,它并不是将新路由添加到浏览器访问历史的栈顶,而是替换掉当前的路由

    在这里插入图片描述

     

    四、HTML5History
    早期History通过back()、forward()、go()等方法,我们可以读取浏览器历史记录栈的信息
    从HTML5开始History提供了2个新的方法:pushState()、replaceState()
    使得我们可以对浏览器历史记录栈进行修改:

    window.history.pushState(data, title, targetURL);
    @状态对象:传给目标路由的信息,可为空
    @页面标题:目前所有浏览器都不支持,填空字符串即可
    @可选url:目标url,不会检查url是否存在,且不能跨域。如不传该项,即给当前url添加data
    1
    2
    3
    4
    window.history.replaceState(data, title, targetURL);
    @类似于pushState,但是会直接替换掉当前url,而不会在history中留下记录
    1
    2
    假定当前网址是example.com/1.html,使用pushState()方法在浏览记录(History 对象)中添加一个新记录。

    var stateObj = { foo: 'bar' };
    history.pushState(stateObj, 'page 2', '2.html');
    1
    2
    添加新记录后,浏览器地址栏立刻显示example.com/2.html,但并不会跳转到2.html,甚至也不会检查2.html是否存在,它只是成为浏览历史中的最新记录。

    这2个方法有个共同的特点:当调用他们修改浏览器历史栈后,虽然当前url改变了,但浏览器不会立即发送请求该url,这就为单页应用前端路由,更新视图但不重新请求页面提供了基础

    更多操作:
     

    history.pushState({page: 1}, 'title 1', '?page=1')
    // URL 显示为 http://example.com/example.html?page=1
    
    history.pushState({page: 2}, 'title 2', '?page=2');
    // URL 显示为 http://example.com/example.html?page=2
    
    history.replaceState({page: 3}, 'title 3', '?page=3');
    // URL 显示为 http://example.com/example.html?page=3
    
    history.back()
    // URL 显示为 http://example.com/example.html?page=1
    
    history.back()
    // URL 显示为 http://example.com/example.html
    
    history.go(2)
    // URL 显示为 http://example.com/example.html?page=3
    
    

    监听地址变化

    在HTML5History的构造函数中监听popState(window.onpopstate)

    popstate事件会在点击后退、前进按钮(或调用history.back()、history.forward()、history.go()方法)时触发。前提是不能真的发生了页面跳转,而是在由history.pushState()或者history.replaceState()形成的历史节点中前进后退
    注意:用history.pushState()或者history.replaceState()不会触发popstate事件。
     

    window.onpopstate = function(event) {
      console.log(event.state);
      console.log(window.history.state;);
    };
    

    以上两种方式皆可获取之前在pushState和replaceState中传入的data

    注意,页面第一次加载的时候,浏览器不会触发popstate事件。

    五、两种模式比较
    pushState设置的新URL可以是与当前URL同源的任意URL;而hash只可修改#后面的部分,故只可设置与当前同文档的URL

    pushState通过stateObject可以添加任意类型的数据到记录中;而hash只可添加短字符串

    pushState可额外设置title属性供后续使用

    history模式则会将URL修改得就和正常请求后端的URL一样,如后端没有配置对应/user/id的路由处理,则会返回404错误

  2. <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <title>pushState</title>
        <style type="text/css">
        .hidden {
            display: none;
        }
        </style>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    </head>
    
    <body>
        <section id="step1" class="step-contain" step="1">
            <p>第1步</p>
            <button class="step-btn" step="1">下一步</button>
        </section>
        <section id="step2" class="step-contain hidden" step="2">
            <p>第2步</p>
            <button class="step-btn" step="2">下一步</button>
        </section>
        <section id="step3" class="step-contain hidden" step="3">
            <p>第3步</p>
        </section>
        <script type="text/javascript">
        $(function() {
            stepProgress();
    
            function stepProgress() {
                var options = {
                    curStep: 1,
                    nextStep: null
                }
                var defaultState={
                    "step": options.curStep,
                     "url": "#step=" + options.curStep
                }
                window.history.pushState(defaultState, "", defaultState.url);
                $(".step-btn").on("click", function() {
                    var step = parseInt($(this).attr("step"));
                    options.nextStep = step + 1;
                    var state = {
                        "step": options.nextStep,
                        "url": "#step=" + options.nextStep
                    }
                    window.history.pushState(state, "", state.url);
                    console.log(state.step)
                    swapStaus(options.nextStep);
                });
    
                function swapStaus(step) {
                    $(".step-contain").each(function() {
                        var tmpStep = $(this).attr("step");
                        if (parseInt(tmpStep) == step) {
                            $("#step" + tmpStep).removeClass("hidden");
                        } else {
                            $("#step" + tmpStep).addClass("hidden");
                        }
                    });
                    options.curStep = step;
                }
    
                $(window).on("popstate",function(){
                    var currentState = history.state;
                    goStep=currentState.step?currentState.step:1;
                    swapStaus(goStep)
                })
            }
    
        })
        </script>
    </body>
    
    </html>
    

    代码:
     

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值