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

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

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

<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>

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

</template>

此种方法通俗,明了,但是缺点是参数直接展示在了请求的url里面,一般可以传递一些标识或者不重要的参数。对于需要保密的一些参数,此种方法不适合。

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

例如:localhost:8080/house

实例如下:

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

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

如下

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

页面取值如下:

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

钩子函数取值:

mounted : function() {

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

}

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

猜你喜欢

转载自my.oschina.net/u/3457493/blog/1812127