<>0. 整体代码:

 【父组件】:
<template> <div> <span style="color: red">------------------------------------
-------</span><br> <span style="color: red">这是父组件页面</span>  <button @click=
"clickParentMethod">点击</button> <SubComponent ref="SubComponent"
@callParentMethod="callParentMethod" trans-data="传递的参数"/> </div> </template> <
script> import SubComponent from "@/components/SubComponent"; export default {
name: "SideOne", components: { SubComponent }, methods: { clickParentMethod () {
console.log('clickParentMethod') this.$refs.SubComponent.callSubMethod() },
callParentMethod (val) { console.log('callParentMethod: ' + val) } } } </script>
 【子组件】:
<template> <div> <span>-------------------------------------------</span><br> <
span>这是子组件页面</span>  <button @click="clickSubMethod">点击</button> </div> </
template> <script> export default { name: "SubComponent", props: { transData: {
type: String } }, methods: { clickSubMethod() { console.log('clickSubMethod')
this.$emit('callParentMethod','回调的参数') }, callSubMethod() { console.log(
'callSubMethod: ' + this.transData) } } } </script>
<>1. 要点:
<SubComponent ref="SubComponent" @callParentMethod="callParentMethod" trans-
data="传递的参数"/>
【整体效果】:

<> 1.1. 父组件调用子组件方法:

* 子组件标签添加ref属性,值为子组件,如ref=“SubComponent”
* 父组件this.$refs.SubComponent.callSubMethod()调用子组件方法
<> 1.2. 子组件回调父组件方法:

* 子组件标签绑定回调方法,如@callParentMethod=“callParentMethod”
* 子组件 this.$emit(‘callParentMethod’,‘回调的参数’)回调父组件方法
* 子路由回调父路由同样适用,在< router-view > 标签内绑定回调方法即可
<> 1.3. 父组件传递参数给子组件:

* 子组件标签绑定参数变量和传递的值,如trans-data=“传递的参数”,也可以使用:transData='param’
形式,param要在data中定义
* 子组件使用props来接收

技术
今日推荐
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:766591547
关注微信