组件传值 父组件向子组件传值
2025年5月7日大约 2 分钟
说明
1在父组件里面的子组件上面绑定动态属性
2在子组件通过props接收传递的数据
3注意:子组件里面声明的属性不要跟父组件的名称相同
4可以传递值,方法,对象,父组件的方法不要加括号(表示不执行)
示例
父组件示例
src/components/pc/home/v_home_list.vue
<template>
<div class="v_home_list">
<div>
{{ title }}
</div>
<hr/>
<div class="one">
<v_byvalue_one :parame="parame_one" :pick="pick" :self="this"></v_byvalue_one>
</div>
</div>
</template>
<script>
import v_byvalue_one from "@/components/pc/home/v_home_byvalue_one.vue";
export default
{
name: 'v_home_list',
data()
{
return {
title:"我是HOME首页列表页",
parame_one:'我是父组件传给组件1的值',
parame_two:'我是父组件传给组件2的值'
};
},
components:
{
v_byvalue_one
},
methods:
{
pick()
{
alert('我是父组件的弹出方法');
}
}
};
</script>
<style lang="css" scoped>
.v_home_list
{
width: 100%;
height: 100%;
background-color: rgba(255, 255, 255, 0.5);
}
.one
{
width: 100%;
height: 40%;
}
</style>
子组件示例 前两种定义prop(不推荐)
src/components/pc/home/v_home_byvalue_one.vue
<template>
<div class="byvalue_one">
<div>
{{ title }}
</div>
<div>
我是父组件传递过来的{{ parame }}
</div>
<div>
<button @click="pick">父弹出</button>
<button @click="getParent()">获取整个父组件对象</button>
</div>
</div>
</template>
<script>
export default {
name: 'byvalue_one',
data()
{
return {
title:"我是组件传值1测试"
};
},
//写法一
props:['parame','pick','self'],
//写法二
props:
{
parame:String,
pick:Function,
self:Object
},
methods:
{
getParent()
{
console.log(this.self);
console.log(this.self.title);
}
}
};
</script>
<style lang="css" scoped>
.byvalue_one
{
width: 100%;
height: 100%;
background-color: rgba(255, 255, 255, 0.5);
}
</style>
子组件示例 第三种种定义prop(推荐)
props:{
user:{
type:Object,
default:()=>{
return {
id:0,
avatar:'https://yiguodu-jizhi.oss-cn-qingdao.aliyuncs.com/cnd/images/avatar.png',
nickname:'往事随风20',
sex:null,
}
},
},
content:{
type:String,
default:'自己的评论会出现删除按钮'
},
star:{
type:String,
default:'3.0'
},
zanNum:{
type:Number,
default:99
},
isMine:{
type:Boolean,
default:false
},
isZan:{
type:Boolean,
default:false
},
create_time:{
type:String,
default:"2020/01/16 13:48:56"
},
},
提示
如果是需要定义数据可能有两种类型可以参考以下做法
实际上就是用数组的写法
props:
{
goodsClassId: {
type: [Number, String],
default: 0
}
},