vue路由跳转页面传参的几种方式记录
1、使用路由url携带参数传递
主页Main.vue模板脚本
<template>
<div class="hello">
<h1>{{msg}}</h1>
<h2>Essential Links</h2>
<div @click="toSlotComo()">Go to SlotTest</div>
</div>
</template>
<script>
export default {
name: 'Main',
data() {
return {
msg: 'Welcome to Your Vue.js App'
}
},
methods: {
toSlotComo() {
this.$router.push({
//把【测试slot插槽】作为参数传递
path: '/soltTest/测试slot插槽'
})
}
}
}
</script>
路由页面SlotTest.vue
<template>
<div>
<div class="top">{{content}}</div>
<my-com>
<p>月落乌啼霜满天,江枫渔火对愁眠</p>
</my-com>
<my-com>
</my-com>
//获取路由传递的参数
<div>{{this.$route.params.myParam}}</div>
</div>
</template>
<script>
export default {
name: 'SlotTest',
data() {
return {
content: ' -----------------------------孤篇横绝------------------------------',
myParam: ''
}
},
components: {
'my-com': {
template: '<div><slot><p>姑苏城外寒山寺,夜半钟声到客船</p></slot></div>'
}
},
}
</script>
路由配置
import Vue from 'vue'
import Router from 'vue-router'
import Main from '@/components/Main'
import SlotTest from '@/components/SlotTest'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Main',
component: Main
},
{
//myParam作为传递参数的key,再参数获取页面使用myParam获取参数
path: '/soltTest/:myParam',
name: 'SlotTest',
component: SlotTest
},
]
})
使用url传参再浏览器页面可以看到传递的参数
2、通过params传递对象
主页Main.vue
<template>
<div class="hello">
<h1>{{msg}}</h1>
<h2>Essential Links</h2>
<!-- <router-link to="/soltTest/测试slot插槽">Go to SlotTest</router-link> -->
<div @click="toSlotComo()">Go to SlotTest</div>
<div @click="toRouteTest()">Go to RouteTest</div>
</div>
</template>
<script>
export default {
name: 'Main',
data() {
return {
msg: 'Welcome to Your Vue.js App'
}
},
methods: {
toRouteTest() {
this.$router.push({
//生命模板名称
name:'MyRouteTest',
//路由传递参数传递一个对象
params:{
name: 'liuping',
age:'31'
}
})
}
}
}
</script>
路由页面RouteTest.vue
<template>
<div>
测试路由传参RouteTest
<div>
//获取路由传递对象的属性
<span>{{this.$route.params.name}} </span>
<span>{{this.$route.params.age}} </span>
</div>
</div>
</template>
<script>
export default {
name:'MyRouteTest',
}
</script>
路由配置
import Vue from 'vue'
import Router from 'vue-router'
import Main from '@/components/Main'
import MyRouteTest from '@/components/RouteTest'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'Main',
component: Main
},
{
//直接配置路由地址即可
path: '/routeTest',
name: 'MyRouteTest',
component: MyRouteTest
}
]
})