Vue 组件传值
Vue 组件之间传值
1. 需求:
1. 父组件调用子组件, 并传值给子组件显示在页面
2. 子组件给父组件传值,父组件接收子组件传来的值
3. 子组件内添加一个input输入框,输入值并修改父组件给子组件传过来的数据
子组件(child.vue):
<template> <div> <p class="p-d">我是父组件传过来的属性:{{childValue}}</p> <div class="p-d"> <input type="text" value="childValue" @change="getActionByInfo" /> </div> <el-divider></el-divider> <div> <p>姓名:{{childObj.username}}</p> <p>年龄:{{childObj.age}}</p> </div> <el-divider></el-divider> <div> <div v-for="(item,index) in childArray" :key="index"> <p>姓名:{{item.name}}</p> <p>性别:{{item.sex}}</p> <p>喜好:{{item.happy}}</p> </div> </div> </div> </template> <script> export default { data(){ return{ } }, props:{ childValue:String, childObj:{ type:Object }, childArray:{ type: Array, default: () => [] }, btnClick:{ type:Function } }, methods: { getActionByInfo(event){ this.$emit('changeValue',event.target.value) } }, } </script> <style scoped> .p-d{ padding: 20px; } </style>
父组件(parent.vue):
<template> <div> <child :childValue="parentValue" :childObj="parentObj" :childArray="parentArray" @changeValue="getValue"></child> </div> </template> <script> import child from '../components/child' export default { name:'parent', components:{ child }, data(){ return{ parentValue:'我是父组件parentValue', parentObj:{ username:'张三', age:22 }, parentArray:[ { name:'张三', sex:'女', happy:'爱学习' }, { name:'李四', sex:'男', happy:'爱玩' } ] } }, methods: { getValue(value){ this.parentValue=value } }, } </script>
2. $parent 和 $children 使用
1. ref为子组件指定一个name名称,通过name来操作子组件;
2. this.$parent 可以直接访问该组件的父实例或组件;
3. 父组件也可以通过this.$children 访问它所有的子组件; 需要注意 $children 并不保证顺序,有几个子组件就显示几个vue实列
2. this.$parent 可以直接访问该组件的父实例或组件;
3. 父组件也可以通过this.$children 访问它所有的子组件; 需要注意 $children 并不保证顺序,有几个子组件就显示几个vue实列
this.$parent
// 在子组件内this.$parent.属性值
mounted() {
this.getChildMsg();
},
methods: {
getChildMsg(){
console.log(this.$parent.parentValue)
}
},
this.$children
//在父组件内用this.$children[下标].属性值
mounted() {
this.getChildrenMsg();
},
methods: {
getChildrenMsg(){
console.log(this.$children[0].childValue)
}
},
ref this.$refs
// ref="组件的别名" <child ref="child2" :childValue="parentValue" :childObj="parentObj" :childArray="parentArray" @changeValue="getValue"></child> methods: { getChildrenMsg(){ console.log(this.$children[0].childValue) // this.$refs.别名 console.log(this.$refs.child2) } },
this.$root
getChildMsg(){
console.log(this.$root)
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下