vue father son value transfer brother value transfer and child father value transfer
- 2021-12-04 09:17:31
- OfStack
1. Parent components pass values to child components
1. Parent Component.vue
// In the parent component
<template>
<div>
<Child ref="child" :title="value"/>
</div>
</template>
<script>
export default {
data() {
return {
value: 'hello world!'
}
}
}
</script>
2. Subcomponent. vue
// In the parent component
<template>
<div>
<span>{{title}}</span>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
default: ''
}
}
}
</script>
//title value is' hello world!
2. Value transfer between sibling components can also be carried out through middleware Bus
$emit
Value transfer
$on
Receive
$off
Delete transport events
1. A component. js
this.$bus.$emit("flag",true)
2. B component. js
mounted() {
this.$bus.$off('flag')
this.$bus.$on('flag', data=> {
this.flag= data
})
}
3. Child components pass values to parent components
1. Parent Component.js
<template>
<div>
<Child ref="child" @getTitle="getTitle"/>
</div>
</template>
<script>
import Child from './components/Child'
export default {
components: {
Child
},
data() {
return {
}
},
method:{
getTitle(data){
console.log(data)
}
}
}
</script>
The printed result is
hello xuliting
2. Subcomponent. js
<template>
<div>
<span>{{title}}</span>
</div>
</template>
<script>
export default {
data() {
return {
title: 'hello xuliting'
}
},
mounted(){
this.getFun()
},
method:{
getFun(){
this.$emit("getTiltle",this.title)
}
}
}
</script>
Summary:
Components can also be solved by passing methods. For example, the parent component is A, and the child components are B and C.
The method that the parent component A calls the child component B is defined as aFun, and the aFun can be passed to the child component C
This is the method pass in the component C in the parent component
<C :a-fun="aFun" />
The reference is in the component C, through props
props: {
aFun: {
type: Function,
default: () => function() {}
}
}
This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!