vue路由传参(两种方法总结)

vue传递参数有多种,据我了解、熟悉的其中两种总结以下:html

1、组件经过query来传递flag参数为1,至关与在 url 地址后面拼接参数 例如:localhost:8080/house?flag=1。 具体实例以下:vue

<template> 安全

<div>  

    <h3>首页</h3>  

    <router-link :to="{ path:'/house', query: { flag: 1} }">  

        <button>点击<tton>  

    </router-link>

    <router-view></router-view>  

</div>

</template> 函数

house.vue页面以下取值:测试

<template> this

<h3>测试路由传参{{ this.$route.query.flag}}</h3>

</template> url

此种方法通俗,明了,可是缺点是参数直接展现在了请求的url里面,通常能够传递一些标识或者不重要的参数。对于须要保密的一些参数,此种方法不适合。code

2、router.push(...),该方法直接将参数存入了路由当中,不会在url地址栏展现。component

例如:localhost:8080/houserouter

实例以下:

this.$router.push({name:'house',params:{flag:1}});

house为脚手架中定义的路由name值。

以下

routes: [ { path: '/'house, name: 'house', component: house }]

页面取值以下:

页面展现:{{this.$route.params.flag}}

钩子函数取值:

mounted : function() {

alert("我是html页面传递过来的参数:----------------------------"+this.$route.params.flag);

}

此种方法不会将参数展现到url里面,比较安全,我的建议传递参数多使用第二种方式。

3、关于传递参数无效的一个实例:

Params

因为动态路由也是传递params的,因此在 this.$router.push() 方法中path不能和params一块儿使用,不然params将无效。须要用name来指定页面。

例如:

this.$router.push({name:'/house',params:{flag:1}});

上面的name为具体跳转的html页面路径,若是不须要携带参数,此处页面也能够跳转成功,如果携带falg参数,则此处会跳转,但参数不会传递成功。

注:此处的name中只能经过路由配置的name属性访问--------------------------------重点

相关文章
相关标签/搜索