For small things, you can also call child component methods with $refs likethis. $refs.foo.bar ()
.
However, direct data reference between components is not recommended.
Component-Vue.js
However, it is also very important to keep the parent and child as separated as possible through a well-defined interface. This ensures that the code for each component is written and judged relatively independently. Therefore, components can be made more maintainable and potentially reusable
So basically
$emit from child to parent
Parent to child props
It may be good to pass data with.
However, props cannot directly call child component methods.
Therefore, there is a way to use EventBus as shown below to coordinate processing between components.
Communication other than parent-child
var EventBus = new Vue ()
Object.defineProperties (Vue.prototype, {
$bus: {
get () {
return EventBus
}
}
}
let ComponentY = Vue.extend ({
mounted () {
this. $bus. $on ('onMountedX', () =>{
console.log ('onMountedX')
})
}
})
let ComponentX = Vue.extend ({
mounted () {
this. $bus. $emit ('onMountedX')
}
components: [ComponentY]
})
Looks good with ref
Use vuex for more complex
If you allow child components to be referenced with the ref attribute, you can call child methods from the parent
The following is a sample program.
The test method of the parent component App.vue calls the method of the child component Test.vue using $refs.
App.vue
<template>
<div id = "app">
<test ref = "test"></test>
<button @ click = "test">test</button>
</div>
</template>
<script>
import Test from "./Test.vue"
export default {
methods: {
test () {
console.log ("parentMethod")
this. $refs.test.childMethod ()
},
},
components: {Test}
}
</script>
No comments:
Post a Comment