通过VueRouter来实现组件之间的跳转:参数的传递,具体内容如下
login —用户名—>main
①明确发送方和接收方
②配置接收方的路由地址
{path:’/myTest’,component:TestComponent}
–>
{path:’/myTest/:id’,component:TestComponent}
③接收方获取传递来的数据
this.$route.params.id
④跳转的时候,发送参数
this.$router.push(‘/myTest/20’)
<router-link :to=”‘/myTest’+id”>跳转</router-link>
代码:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>传参</title>
<script src="js/vue.js"></script>
<script src="js/vue-router.js"></script>
</head>
<body>
<div id="container">
<p>{{msg}}</p>
<!--指定容器 -->
<router-view></router-view>
</div>
<script>
//创建主页面组件
var myMain = Vue.component("main-component",{
//保存登录传递过来的数据
data:function(){
return {
uName:''
}
},
template:`
<div>
<h1>主页面用户名:{{uName}}</h1>
</div>
`,
//挂载该组件时自动拿到数据
beforeMount:function(){
//接收参数
console.log(this.$route.params);
this.uName = this.$route.params.myName ;
}
})
//创建登录页面组件
var myLogin = Vue.component("login-component",{
//保存用户输入的数据
data:function(){
return {
userInput:""
}
},
methods:{
toMain:function(){
//跳转到主页面,并将用户输入的名字发送过去
this.$router.push("/main/"+this.userInput);
console.log(this.userInput);
}
},
template:`
<div>
<h1>登录页面</h1>
<input type="text" v-model="userInput" placeholder="请输入用户名">
<button @click="toMain">登录到主页面</button>
<br>
<router-link :to="'/main/'+userInput">登录到主页面</router-link>
</div>
`
})
var NotFound = Vue.component("not-found",{
template:`
<div>
<h1>404 Page Not Found</h1>
<router-link to="/login">返回登录页</router-link>
</div>
`
})
//配置路由词典
const myRoutes = [
{path:"",component:myLogin},
{path:"/login",component:myLogin},
//注意冒号,不用/否则会当成地址
{path:"/main/:myName",component:myMain},
//没有匹配到任何页面则跳转到notfound页面










