Foreword:
Communication between parent and child components of vue3.0
table of Contents:
From father to son: provide / inject
But the method of use in vue3.0 is changed, because the setup does not support direct use of this
1. Get the fields defined in the setup of the parent component
2. Call the method defined in the setup of the parent component
This is what the official said: official entrance
From father to son:
provide / inject details
From son to father:
Subassembly:
<el-button @click="changeParentNum('111')">点我给父组件发数据</el-button>
setup (props, ctx) {
const changeParentNum = data => {
// 通过ctx调用emit事件 需要注意的是Vue2.x中使用 $emit切勿混淆
ctx.emit('handle', data)
}
return {
changeParentNum
}
}
Parent component:
<Table @handle="handleFun"></Table>
import { ElMessage} from 'element-plus'
setup() {
function handleFun(data) {
ElMessage.success({
message: data,
type: 'success'
})
}
return {
handleFun,
}
}
other:
We can use this.$parent.+parent component's method name/parent component's property name in vue2.0 to directly use the field defined by the parent component's data or call the method
But the method of use in vue3.0 is changed, because the setup does not support direct use of this
1. Get the fields defined in the setup of the parent component
import { getCurrentInstance } from 'vue'
setup (props, ctx) {
const { proxy } = getCurrentInstance()
let a = proxy.$parent.state
}
2. Call the method defined in the setup of the parent component
import { getCurrentInstance } from 'vue'
setup (props, ctx) {
const { proxy } = getCurrentInstance()
proxy.$parent.handleFun('我调用父亲')
}
This is what the official said: official entrance
#$parent
-
Types of:
Vue instance
-
Readable only
-
detailed:
The parent instance, if the current instance has one
-