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