Objective: To understand the way events are passed between vUE’s parent and child components (one of them) through a small example of an accordion. The vUE instance uniquely identifies the actual use of _UID.

Recommended reading time: 3 minutes

The accordion, which has two components,
and
, has two functions:

  1. Click on the child component<collapse-item>The parent component needs to know who was clicked
  2. The parent notifies all of his child components that component A has been clicked, component B, C… The content of the child element is completely hidden

Fact: Each Vue instance has an incremented ID, which can be obtained by this._uid

Code implementation:

1. Define a parent component Collpase to implement the following functions

  1. Mount the cut method, pass in the Id of the instance that was clicked, and iterate through the child components to confirm who was clicked
  2. Children that are not clicked have their show property set to false
/ / into the vue
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
// Define a parent component collapse
Vue.component('Collapse', {
  methods: {
    cut(childId) {
      this.$children.forEach(child= > {
        console.log('ci', child._uid)
        if(child._uid ! == childId) { child.show =false; }}); }},template: `
      
`
}) Copy the code

2. Define a subcomponent CollpaseItem to implement the following functions

  1. Accept a tile as the title
  2. Data maintains a show property that controls content display and hiding
  3. When title is clicked, the parent component’s cut method is called with this.$parent, passing in the _uid of the currently clicked instance
  4. Set the show property of the current component to true
Vue.component('CollapseItem', {
  props: ['title'],
  data() {
    return {show: false}},methods: {
    change() {
      console.log(this._uid)
      this.$parent.cut(this._uid);
      this.show = !this.show; }},template: `
      
{{title}}
`
}) Copy the code

3. Instance mount, Dom render, complete.

<div id="app">
<collapse>
  <collapse-item title="react">The content of 1</collapse-item>
  <collapse-item title="vue">Content of the 2</collapse-item>
  <collapse-item title="nodejs">Content of the 2</collapse-item>
</collapse>
</div>
<script>
let vm = new Vue({
  el: '#app'
})
</script>
Copy the code

Thanks for reading!

I am Haiming Yue, a primary school student.