vue3.0父子组件的通信

前言:

      vue3.0父子组件的通信

目录:

父传子:provide / inject

子传父:

子组件:

父组件:

其他:

我们vue2.0中可以使用  this.$parent.+父组件的方法名/父组件的属性名  直接使用父组件的data定义的字段或者调用方法

但是在vue3.0中使用方法是改变了,因为setup里面不支持直接使用this

1、获取父组件的setup里面定义的字段

2、调用父组件的setup里面定义的方法

官方是这样说的:官方入口

#$parent


父传子:

            provide / inject 详情

子传父:

子组件:

 <el-button @click="changeParentNum('111')">点我给父组件发数据</el-button>

 setup (props, ctx) {
    const changeParentNum = data => {
      // 通过ctx调用emit事件 需要注意的是Vue2.x中使用 $emit切勿混淆
      ctx.emit('handle', data)
    }
     return {
      changeParentNum
    }
  }

父组件:

<Table @handle="handleFun"></Table>


import { ElMessage} from 'element-plus'
setup() {
    function handleFun(data) {

      ElMessage.success({
        message: data,
        type: 'success'
      })
    }
    return {
      handleFun,
    }
  }

其他:

我们vue2.0中可以使用  this.$parent.+父组件的方法名/父组件的属性名  直接使用父组件的data定义的字段或者调用方法

但是在vue3.0中使用方法是改变了,因为setup里面不支持直接使用this

1、获取父组件的setup里面定义的字段


import { getCurrentInstance  } from 'vue'
setup (props, ctx) {
    const { proxy } = getCurrentInstance()
    let a = proxy.$parent.state
}

2、调用父组件的setup里面定义的方法

import { getCurrentInstance  } from 'vue'
setup (props, ctx) {
    const { proxy } = getCurrentInstance()
    proxy.$parent.handleFun('我调用父亲')
}

官方是这样说的:官方入口

#$parent

  • 类型:Vue instance

  • 仅可读

  • 详细:

    父实例,如果当前实例有的话

相关资料:

https://www.cnblogs.com/qt-fei/p/14264290.html

猜你喜欢

转载自blog.csdn.net/qq_41619796/article/details/114285552