vue 页面间传值

使用params传参 ,不能使用path 只能使用name

使用params传参,刷新参数会消失

router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import login from '@/components/login/login'
import index from '@/components/index/index'
import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path:'/index',
      name : 'index',
      component : index
    },
    {
      path:'/login',
      name : 'login',
      component : login
    }
  ]
})

login页面(params传参)

this.$router.replace({name:'index',params:{
                       username:successResponse.data.object.username,
                       phone:successResponse.data.object.phone
                       }
                       })

index页面

<template>
    <div>  
        <hr>
        <div>
            This is username. <span v-text="username"> </span>  <br> 
            This is the phone. <span v-text="phone"> </span> <br> 
             This is also username {{$route.params.username}}   
        </div>
        <hr> 
    </div>
</template>
<script>
export default {
    name : 'index',
    //created  钩子函数  Vue 初始化时执行
    created:function() {
        this.getParams();
    },
    watch:{
        //监测路由变化,只要变化了就调用路由参数方法将数据存储本组件即可
        '$route':'getParams'
    },
    methods:{
        getParams:function() {
            //取得路由带过来的参数
            let routeUsername = this.$route.params.username
            let routePhone = this.$route.params.phone
            //将数据放在当前组件的数据内
            this.username = routeUsername
            this.phone = routePhone
        },
    }
}
</script>

login页面(query传参)

this.$router.replace({path:'/index',query:{
                       username:successResponse.data.object.username,
                       phone:successResponse.data.object.phone
                       }
                       })

index页面

<template>
    <div>
        
        <hr>
        <div>
            This is username. <span v-text="username"> </span>  <br> 
            This is the phone. <span v-text="phone"> </span> <br> 
             This is also username {{$route.query.username}}    
        </div>
        <hr>
        
    </div>
</template>
<script>
export default {
    name : 'index',
    //created  钩子函数  Vue 初始化时执行
    created:function() {
        this.getQuerys();
    },
    watch:{
        //监测路由变化,只要变化了就调用路由参数方法将数据存储本组件即可
        '$route':'getQuerys',
    },
    methods:{
        getQuerys:function() {
            //取得路由带过来的参数
            let routeUsername = this.$route.query.username
            let routePhone = this.$route.query.phone
            //将数据放在当前组件的数据内
            this.username = routeUsername
            this.phone = routePhone
        },
    }
}
</script>

原文地址:https://www.cnblogs.com/lick468/p/10973021.html