前言
前期我用props以及$emit()等方法来实现父子组件之间的相互传值。
【Vue实战】自定义组件数据传值以及组件动态切换实例
想看的小伙伴可以点击进去浏览哦~
后面学习了vue-cli脚手架之后,关于在脚手架上来搭建这个学生信息表的项目,则需要改写一些代码了,其中会涉及到动态路由的传值问题,接下来我们一步步来看代码。
一、动态路由是什么?
首先,我们先来了解一下什么叫做动态路由?
vue的单页面应用是基于路由和组件的,路由用于设定访问路径,并将路径和组件映射起来。
传统的页面应用,是用一些超链接来实现页面切换和跳转的。
在vue-router单页面应用中,则是路径之间的切换,也就是组件的切换。
简单的来理解就是:在点击不同的组件进行切换时,路由会跟着动态地切换啦~
二、效果+代码
1.动态表格的添加
在此动态表格的添加模块中,我们要涉及到如何把用户输入的信息(子组件)添加到学生信息表(父组件)中去呢?
此时,我们在运用动态路由的情况下可以在子组件处用
this.$router.push方法去设置对象,在父组件处用this.route.params去接收对象所携带的数据。
//子组件:userMessage.vue 设置this.$router.push
methods: {
add: function () {
this.$router.push({
name:"userManager",
params:{
num:this.person.num,
name:this.person.name,
sex:this.person.sex,
age:this.person.age,
hobby:this.person.hobby,
imgsrc:this.person.imgsrc
}
}),
//定义其父组件的一个方法,用来添加数组
this.$parent.inputMessage()
}
}
//父组件:userManager.vue $route.params来接收数据
methods: {
//前面子组件所定义的父组件的添加数组的方法
//先是接收到子组件传过来的数据,再添加进persons的数组里面去
inputMessage:function(){
this.persons.push({
num:this.$route.params.num,
name:this.$route.params.name,
sex:this.$route.params.sex,
age:this.$route.params.age,
hobby:this.$route.params.hobby,
imgsrc:this.$route.params.imgsrc,
}),
this.showBox=false
}
2.用户详情页面的查看
在此查看用户详情信息的模块中,我们同样也在动态路由的情况下使用其传值方法,方法和上面提到的基本是差不多的~
//父组件:userManager.vue 传数据
methods: {
showdetail:function(index){
this.$router.push({
name:'userMessage2',
params:{
num:this.persons.[index].num,
name:this.persons[index].name,
sex:this.persons[index].sex,
age:this.persons[index].age,
hobby:this.persons[index].hobby,
imgsrc:this.persons[index].imgsrc
}
})
this.showBox = true;
}
//子组件:userMessage2.vue 接收以及显示数据
<template id="mycomponent2">
<div>
<!-- <div><button type="button" v-on:click="guanbia()">X</button></div> -->
<div>
<div>
<table class="secondcontainer">
<tr>
<td colspan="15">
<div class="p-content">
<p>学号:{{$route.params.num}}</p>
<p>姓名:{{$route.params.name}}</p>
<p>性别:{{$route.params.sex}}</p>
<p>年龄:{{$route.params.age}}</p>
<p>专长:{{$route.params.hobby}}</p>
</div>
<img v-bind:src="$route.params.imgsrc" class="myPersonImg" >
</td>
</tr>
</table>
</div>
</div>
</div>
</template>
下一篇博客我会把代码继续完善,将此份学生信息表的添加,查看详情的完整代码贴出来并详细解析~
如果此篇博客能帮得到你,欢迎大家关注,点赞,评论,收藏,转发~
如有不足也请在评论区提出批评指正!多多指教!