当前位置: 首页 > news >正文

Vue2——父子之间间的调用

1、父组件给子组件传值使用props

父组件:
<div><SonPage  msg="通过props传递值---父=>子" ></SonPage><h1>父组件</h1></div>
子组件
<div :style="{border: '1px solid red'}"><h1>子组件</h1><div>我是父组件传入的参数:{{ msg }}</div>
</div>
<script>
export default {props: {msg: {type: String,}},name: "SonPage",
}
</script>

2、父组件调用子组件方法

父组件

使用 this.$refs.sonRef.子组件方法名。父组件在使用子组件时要加ref,上下一致

<template><div><SonPage ref="sonRef" ></SonPage><h1>父组件</h1><button @click="opSon">我要调用子组件</button></div>
</template><script>
import SonPage from "@/views/SonPage";export default {name: "pPage",components: {SonPage},methods: {opSon() {this.$refs.sonRef.ParentOpSon("我是父组件调用子组件方法传入的参数");},},
}
</script>
子组件
<template><div :style="{border: '1px solid red'}"><h1>子组件</h1><div>这里是父组件调用子组件方法传入的参数:{{ msg2 }}</div></div>
</template><script>
export default {name: "SonPage",data() {return {msg2: ""}},methods: {ParentOpSon(parentMsg) {this.msg2 = parentMsg;},},
}
</script><style scoped></style>
结果:

3、子组件调用父组件方法

父组件

使用子组件标签上加@【子组件的this.$emit中第一个参数名】。方法使用 e就是子组件的参数

<template><div><SonPage @opParent="parentMethod"></SonPage><h1>父组件</h1><div>我是子组件调用父组件方法传入的参数{{ sonMsg }}</div></div>
</template>
<script>
import SonPage from "@/views/SonPage";export default {name: "pPage",components: {SonPage},data() {return {sonMsg: ""}},methods: {parentMethod(e) {console.log(e);this.sonMsg = e;}},}
</script><style scoped></style>
子组件

子组件中使用this.$emit("父组件标签上的@的名"," 调用父组件方法的参数")

<template><div :style="{border: '1px solid red'}"><h1>子组件</h1><button @click="opParent">我要调用父组件的方法</button></div>
</template><script>
export default {name: "SonPage",data() {return {msg2: ""}},methods: {opParent() {this.$emit("opParent", "我是子组件调用父组件方法传入的参数")}},
}
</script><style scoped></style>
结果:

三种传值方法都是比较常用的

整理不全面,多多指教~

http://www.lryc.cn/news/429253.html

相关文章:

  • xfs Vs ext4?
  • 数据结构stack (笔记)
  • SQL - 创建 表和数据库
  • 使用 Arch Linux 几个月有感 | 为什么我选择 Arch Linux ,Arch 的优缺点有什么 | 一些Linux发行版推荐
  • SQLserver中的增删改查和数据类型
  • 个人收藏个性化、实用性、可玩性在线网站持续更新,与君共享
  • win10蓝牙只能发送,无法接收
  • 【论文阅读03】用于海洋物体检测的多注意力路径聚合网络
  • Linux 进程(2)
  • [CSCCTF 2019 Qual]FlaskLight1
  • layui table表单 checkbox选中一个其它也要选中
  • 【pip镜像设置】pip使用清华镜像源安装
  • c++ 智能指针--std::shared_ptr
  • 网络工程师学习笔记(二)
  • 90.WEB渗透测试-信息收集-Google语法(4)
  • 阿里Qwen2开源大模型本地部署及调试全攻略
  • 『功能项目』移动后的光标显示【04】
  • HTML 基本语法特性与 title 标签介绍
  • CSS的:placeholder-shown伪类:精确控制输入框占位符样式
  • Java之HashMap的底层实现
  • 多张图片进行模型重建并转换为OBJ模型
  • 信息安全保证人员CISAW:安全集成
  • 别再无效清理微信内存啦,这才是正确清理内存的方式
  • ant design 的 tree 如何作为角色中的权限选择之一
  • 如何在项目管理中完成项目立项?
  • LearnOpenGL——延迟渲染学习笔记
  • 惠海H4312 dcdc同步整流降压恒压IC 30V 40V转3.3V/5V/12V小体积大电流单片机供电
  • [Linux]如何在虚拟机安装Ubuntu?(小白向)
  • keepalived详解
  • 工业设备中弧形导轨的检测标准是什么?