轉(zhuǎn)自: https://blog.csdn.net/wy01272454/article/details/77869442?locationNum=7&fps=1
傳參方式
- 通過(guò)router-link進(jìn)行跳轉(zhuǎn)
- 通過(guò)編程導(dǎo)航進(jìn)行路由跳轉(zhuǎn)
- 動(dòng)態(tài)路由
一崖咨、router-link方式
<router-link
:to="{
path: 'yourPath',
params: {
name: 'name',
dataObj: data
},
query: {
name: 'name',
dataObj: data
}
}">
</router-link>
1. path -> 是要跳轉(zhuǎn)的路由路徑,也可以是路由文件里面配置的 name 值,兩者都可以進(jìn)行路由導(dǎo)航
2. params -> 是要傳送的參數(shù),參數(shù)可以直接key:value形式傳遞
3. query -> 是通過(guò) url 來(lái)傳遞參數(shù)的同樣是key:value形式傳遞
// 2,3兩點(diǎn)皆可傳遞
二主之、編程方式傳參
// 組件A
// 組件 a
<template>
<button @click="sendParams">傳遞</button>
</template>
<script>
export default {
name: '',
data () {
return {
msg: 'test message'
}
},
methods: {
sendParams () {
this.$router.push({
path: 'yourPath',
name: '要跳轉(zhuǎn)的路徑的 name,在 router 文件夾下的 index.js 文件內(nèi)找',
params: {
name: 'name',
dataObj: this.msg
}
/*query: {
name: 'name',
dataObj: this.msg
}*/
})
}
},
computed: {
},
mounted () {
}
}
</script>
<style scoped></style>
// 組件B
<template>
<h3>msg</h3>
</template>
<script>
export default {
name: '',
data () {
return {
msg: ''
}
},
methods: {
getParams () {
// 取到路由帶過(guò)來(lái)的參數(shù)
let routerParams = this.$route.params.dataobj
// 將數(shù)據(jù)放在當(dāng)前組件的數(shù)據(jù)內(nèi)
this.msg = routerParams
}
},
watch: {
// 監(jiān)測(cè)路由變化,只要變化了就調(diào)用獲取路由參數(shù)方法將數(shù)據(jù)存儲(chǔ)本組件即可
'$route': 'getParams'
}
}
</script>
<style scoped></style>
三逞刷、動(dòng)態(tài)路由方式
設(shè)置動(dòng)態(tài)路由: path: '/user/:id'
獲取參數(shù): $route.params.id
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<p>
<router-link to="/user/foo">/user/foo</router-link><br>
<router-link to="/user/bar">/user/bar</router-link>
</p>
<router-view></router-view>
</div>
<script>
const User = {
template: `<div>User {{ $route.params.id }}</div>`
}
const router = new VueRouter({
routes: [{
path: '/user/:id',
component: User
}]
})
const app = new Vue({
router
}).$mount('#app')
</script>