params传参
this.$router.push({name: 'index'}, params: {id: item.id})
this.$router.params.id
路由属性传递
this.$router.push({name: '/index/${item.id}'})
// 路由配置 {path: '/index/:id'}
query传参(可以解决页面刷新参数的丢失问题)
this.$router.push({
name: 'index',
query: {id: item.id}
})
Vue2中的路由配置以及demo
router/index.js
import VueRouter from 'vue-router'
import Vue from 'vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
// name: '/',
component: () => import('@/view/test.vue')
},
{
path: '/test',
name: 'test',
component: () => import('@/view/test-b.vue')
},
{
path: '/test-c/:id',
name: 'test-c',
component: () => import('@/view/test-c.vue')
},
{
path: '/test-d',
name: 'test-d',
component: () => import('@/view/test-d.vue')
},
]
const router = new VueRouter({
routes
})
export default router
main.js
import Vue from 'vue'
import App from './App.vue'
import router from '@/router/index'
import VueRouter from 'vue-router'
Vue.config.productionTip = false
Vue.use(VueRouter)
new Vue({
router,
render: h => h(App),
}).$mount('#app')
app.vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'App',
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
test.vue
<template>
<div class="test">
测试A
<button @click="changeUrl('test')">跳转页面至testB</button>
<button @click="changeUrl('test-c')">跳转页面至testC</button>
<button @click="changeUrl('test-d')">跳转页面至testD</button>
</div>
</template>
<script>
export default {
name: 'test-a',
methods: {
changeUrl(name) {
if(name == 'test') {
this.$router.push({name, params: {id: "12345"}})
} else if(name == 'test-c') {
this.$router.push(`/${name}/123456`)
} else {
this.$router.push({name, query: {id: "12345"}})
}
}
}
}
</script>
<style scoped>
</style>
test-b.vue
<template>
<div class="test">
<p>测试B</p>
<p>{{ msg }}</p>
<button @click="changeUrl">跳转页面至testA</button>
</div>
</template>
<script>
export default {
name: 'test-b',
data() {
return {
msg: ""
}
},
mounted() {
this.msg = this.$route.params.id
},
methods: {
changeUrl() {
this.$router.push('/')
}
},
}
</script>
<style scoped>
</style>
test-c.vue
<template>
<div class="test">
<p>测试C</p>
<p>{{ msg }}</p>
<button @click="changeUrl">跳转页面至testA</button>
</div>
</template>
<script>
export default {
name: 'test-c',
data() {
return {
msg: ""
}
},
mounted() {
this.msg = this.$route.params.id
},
methods: {
changeUrl() {
this.$router.push('/')
}
},
}
</script>
<style scoped>
</style>
test-d.vue
<template>
<div class="test">
<p>测试D</p>
<p>{{ msg }}</p>
<button @click="changeUrl">跳转页面至testA</button>
</div>
</template>
<script>
export default {
name: 'test-d',
data() {
return {
msg: ""
}
},
mounted() {
this.msg = this.$route.query.id
},
methods: {
changeUrl() {
this.$router.push('/')
}
},
}
</script>
<style scoped>
</style>