第一步:定义路由文件 router >index.js如下
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import home from '@/components/Home'
import router1 from '@/components/Router1'
import router2 from '@/components/Router2'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/home',
name: 'home',
component: home
},
{
path: '/router1',
name: 'routerNum1',
component: router1
},
{
path: '/router2',
name: 'routerNum2',
component: router2
},
]
})
第二步:home.vue组件文件代码如下
<template>
<div class="hello">
<h3>{{ msg }}</h3>
<button @click="goBack()">js编程式go方法返回history页面</button>
<hr>
<h3>js编程式导航中push方法的使用:</h3>
<button @click="pathTo()">push方法的url参数使用path值导航</button>
<button @click="pathObjectTo()">push方法的url参数使用path对象导航</button><br>
<button @click="nameObjectTo()">push方法,包含路由命名name键值的对象导航</button><br>
<button @click="nameParamTo()">push方法,包含路由命名name键值的对象结合params传参</button><br>
<button @click="pathParamTo()">push方法,path键值对象导航结合params传参,参数传递失败</button>
<button @click="pathQueryTo()">push方法,path键值对象导航结合query传参</button><br>
<button @click="pathandTo()">push方法,path值拼接参数来传参</button>
</div>
</template>
<script>
export default {
name: 'Home',
data () {
return {
msg: 'Welcome to Home 主页!!!!'
}
},
methods:{
goBack:function(){
this.$router.go(-1);
},
pathTo:function(){ //使用路由的path值
this.$router.push("/router1");
},
pathObjectTo:function(){ //使用包含路由path键值的对象
this.$router.push({path:'/router1'});
},
nameObjectTo:function(){ //使用包含路由name键值的对象
this.$router.push({name:'routerNum1'});
},
nameParamTo:function(){ //使用包含name键值和params参数对象的对象
this.$router.push({name:'routerNum1',params:{userId:123}});
},
pathParamTo:function(){ //path键值结合params的形式传参无效
this.$router.push({path:'/router1',params:{userId:123}});
},
pathQueryTo:function(){ //可以使用path键值结合query的形式传参
this.$router.push({path:'/router1',query:{userId:123}});
},
pathandTo:function(){
const userId=123;
this.$router.push({path:`/router1/${userId}`});
}
}
}
</script>
<style scoped>
h1, h2 {
color:red;
}
</style>
第三步:router1.vue组件代码如下,使用this.$route.params.paramName或query.queryName接收路由传的参数。
<template>
<div class="hello">
<h3>{{ msg }}</h3>
<button @click="goBack()">js编程式go方法上一个路由页面</button>
<p>{{fromRouterParams}}</p>
<p>{{fromRouterQuery}}</p>
</div>
</template>
<script>
export default {
name: 'Router1',
data () {
return {
msg: 'Welcome to Router1' ,
fromRouterParams:this.$route.params.userId,
fromRouterQuery:this.$route.query.userId,
}
},
methods:{
goBack:function(){
this.$router.go(-1);
},
}
}
</script>
<style scoped>
h1, h2 {
color:red;
}
</style>