1. 作用:不借用<router-link>实现路由跳转,让路由跳转更加灵活
2. 具体编码:
//Message.vue
<template>
<div>
<ul>
<li v-for="m in messageList" :key="m.id">
<router-link
:to="{
name: 'xiangqing',
query:{
id: m.id,
title: m.title
}
}">
{{ m.title }}
</router-link>
</li>
<button @click="pushShow(m)">push查看</button>
<button @click="replaceShow(m)">replace查看</button>
</ul>
<hr>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'Message',
data() {
return {
messageList:[
{id: '001',title: '消息001'},
{id: '002',title: '消息002'},
{id: '003',title: '消息003'}
]
}
},
methods: {
pushShow(m) {
this.$router.push({
name: 'xiangqing',
query:{
id: m.id,
title: m.title
}
})
}
},
replaceShow(m) {
this.$router.replace({
name: 'xiangqing',
query:{
id: m.id,
title: m.title
}
})
}
}
</script>
//Banner.vue
<template>
<div class="col-xs-offset-2 col-xs-8">
<div class="page-header">
<h2>Vue Router Demo</h2>
<button @click="back">前进</button>
<button @click="forward">后退</button>
<button @click="test">测试一下go</button>
</div>
</div>
</template>
<script>
export default{
name: 'Banner',
methods:{
//后退
back(){
//console.log(this.$router) 可查阅路由相关api
this.$router.back()
},
//前进
forward(){
this.$router.forward()
},
//可前进也可后退
test(){
this.$router.go(-2) //-2代表后退2步,数字代表具体的步数,正数代表前进负数代表后退
}
}
}
</script>
文章展示了在Vue中如何不使用<router-link>进行路由跳转,通过组件内的方法调用this.$router.push和this.$router.replace实现。同时在Banner.vue组件中,演示了如何利用$router的back、forward和go方法控制浏览历史。
1185

被折叠的 条评论
为什么被折叠?



