zoukankan      html  css  js  c++  java
  • vue-router几大坑

    如今vue使用率很高,踩坑这就是很平常的了,使用了几年坑都依然没踩完,纠结呀

    一、router.js配置要点

    大家都知道vue 是组件化开发,页面很多路由难免,
    在这里插入图片描述
    这里是路由配置router.js

    最外层是 new Router创建router 实例,该实例里面是多个route配置

    注意:这里实例是一个 Router 而 其中参数是routes千万别写成routers

    二、params与query

    参数传递,可以使用params和query的方式进行参数传递
    需要注意的是

    1. router为VueRouter实例,想要导航到不同URL,则使用router.push方法
    2. $route为当前router跳转对象,里面可以获取name、path、query、params等

    1、使用 params进行参数传递

    OK现在开始配置路由
    在这里插入图片描述
    这里配置了一个路由跳转到子界面,并且带一个参数过去,

    在这里插入图片描述
    这个页面接收上一个页面传入的参数

    看来很简单是吧,就这样就可以了?

    no这个并没像想象的那么简单,这个getParams打印出来是一个undefined当时就觉得奇怪了,为什么会无法把参数传递过来呢!

    2、name 与path使用场景

    看来一圈原来是

    
    params传参,push里面只能是 name:'xxxx',不能是path:'/xxx',因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!!!
    
    

    于是修改参数传递

    	console.log('修改完成')
    	this.$router.push({name: 'systemManage', params:{ keepActive: 'userManage' }})
    	}
    

    同时修改接收参数的方法

    created(){
    	// 获取操作后的参数
    	const getParams = this.$route.params
    	console.log(getParams)
    

    看这里接收后的参数不再是undefined了
    在这里插入图片描述

    但是这个虽然不是undefined但是也不是我需要的参数呀,

    3、当前路由对象指定错误

    感觉很奇怪,于是把this.$route打印出来看看

    在这里插入图片描述

    看当前this.$route这个路由实例的name 是 SystemIndex,而 systemIndex 应该是父页面路由的

    name,上面使用this.$route 根据当前route实例来获取参数自然没有了

    在这里插入图片描述

    于是修改父页面参数配置,将其name 指定到当前route 实例上去,如:

    	console.log('修改完成')
    	this.$router.push({name: 'SystermIndex', params: {id: 'userManage' }})
    	}
    

    在这里插入图片描述
    看如图,再次在子页面 console 发现params 中已经有父页面传过来的参数了,证明这已经ok

    总结】:路由使用 this.$router({name: 路由名称, params: {参数key: 参数值 }})进行页面跳

    转参数传递,子页面使用 this.$route.params 进行参数获取。

    4、使用query进行参数传递

    有了上面坑的经历,这里使用query就很轻松了

    query直接使用 path 就行了

    	console.log('修改完成')
    	this.$router.push({this.$route.meta.activeMenu, query: {id: 'userManage' }})
    	}
    

    获取参数

    created(){
    	// 获取操作后的参数
    	const getParams = this.$route.query
    	console.log(getParams)
    
  • 相关阅读:
    [React] Styled System with extendable Box element
    [CSS] Use grid-template to make your CSS Grid declarations more readable
    [Machine Learning Ex2] Linear Regression with Multiple Variables
    [Machine Learning] Normal Equation for linear regression
    [React] Use react styled system with styled components
    [Machine Learning] Polynomial Regression
    [Machine Learning] Gradient Descent in Practice I
    IT 运行在云端,而云运行在 Linux 上
    html+php超大视频上传代码
    html+php超大视频上传源代码
  • 原文地址:https://www.cnblogs.com/dengxiaoning/p/13336789.html
Copyright © 2011-2022 走看看