Examples of eight methods for vue to realize component communication

  • 2021-11-14 04:58:46
  • OfStack

Directory 1, props parent component-- > Subcomponent communication 2. $emit subcomponent-- > Parent component passing 3. bus (Event Bus) sibling component communication 4. $parent, $children access component instances directly 5. $refs 6. provide/inject (provide/inject) multi-component or deep-level component communication 7. slot (slot-scope scope slot) child element-- > Parent element (similar to communication) 8. vuex status management Summarize

Messaging between components is very important for vue, and the following is my summary of the common ways of messaging between components

1. props Parent Component-- > Subcomponent communication

Parent Component-Pass values to child components in the way of attributes

Subcomponent-props mode to receive data


<Son :datas="fData"></Son>

<script>
import Son from '@/components/son'
  export default{
    name:'Father',
    components:{Son},
    data(){
      return{
        fData:' I am the value passed by the parent component to the child component -props Mode '
      }
    }
  }
</script>

The parameter name accepted by the child component props is the same as the attribute name 1 defined when the parent component is passed


<template>
  <div> I am the data of the parent component: {{fData}}</div>
  <div @click=changeData> I am the parent component passing the modified data: {{mydata}}</div>
</template>
<script>
  export default{
    name:'Son',
    props:{
      fData:{
        type:String,
        default:''
      }
    }
    data(){
      mydata:this.fatherData
    },
    methods:{
     changeData(){
        this.mydata += ' Change data '
      }
    },
  }
</script>

Note:

The child component cannot directly modify the value passed by the parent component: Because of the one-way data flow mechanism of Vue, if the value of the parent component is directly modified, it will be "polluted". (props is one-way bound (read-only property): when the property of the parent component changes, it is passed to the child component, but not the other way around)
The error message is probably: vue communication error using prop: Avoid mutating a directly since the value will be whenever the parent Solution: One variable mydata can be defined in the subcomponent to receive fData data Parameter passing type uncertainty can be written as follows:

props:{
    fData:{
        type:[String,Number],
        default:''
    }
}

2. $emit subcomponent-- > Parent component passing

Subcomponent binding custom events
The first parameter of $emit () is the custom event name, and the second parameter is the data to be passed
Use $emit () to trigger changes to data

Subcomponent


<el-button @click="handleEmit"> Change the parent component </el-button>

<script>
 export default{
   name:'Son',
   methods:{
     handleEmit(){
       this.$emit('triggerEmit',' Data of subcomponents ')
     }
   }
 }
</script>

Parent component (the name of the event sent by the child component, the name of the event to be accepted by the parent component 1)


<Son @triggerEmit="changeData"></Son>

<script>
 import Son from '@/components/son'
 export default{
   name:'Father',
   components:{Son},
   methods:{
     changeData(name){
       console.log(name) // =>  I am data from subcomponents 
     }
   }
 }
</script>

$emit and props combined with sibling component value transfer

The parent component introduces two child components The parent component acts as a bridge

Parent component


<childA :myName="name"></ChildA>
<ChildB :myName="name" @changeName="editName"></ChildB>  
    
export default{
  data() {
    return {
      name: ' Hello data '
    }
  },
  methods: {
    editName(name){
      this.name = name
    }
  }
}

Subcomponent B changes, receiving data

< p > Name: {{myName}} < /p >


<button @click="changeName"> Change one's name </button>
    
<script>
export default{
  props: {
    myName:String
  },
  methods: {
    changeName() {
      this.$emit('changeName', ' New data name ')
    }
}
}
</script>

Subcomponent A receives data


<p> Name: {{ newName }}</p>
    
<script>
export default{
  props: {
    myName:String
  }
}
</script>

3. bus (Event Bus) sibling component communication

Non-parent component or more hierarchical component-to-component value transfer is managed by a separate event center in Vue

Create a public bus. js file Expose the Vue instance To transfer data, bus is triggered by one event. $emit (method name, transferred data) The receiving party listens through bus. $on (method name, [params]) in the life cycle function Destroy event, the receiving party cannot monitor the data after being destroyed by bus. $off (method name)

import Vue from "vue"
const bus=new Vue()
export default bus

Calls are defined in components that need to change data


<template>
  <div>
    <div> I am the communication component A</div>
    <button @click="changeName"> Change one's name </button>
  </div>
</template>

<script>
import bus from "@/utils/Bus.js";
export default {
  components: {},
  data() {
    return {};
  },
  mounted() {
    console.log(bus);
  },
  methods: {
    changeName() {
      bus.$emit("editName", " Data set! ");
    },
  },
};
</script>

<style lang='scss' scoped>
</style>

Another component also introduces bus. js file to listen for event callbacks through $on


<template>
  <div> I am the data of the parent component: {{fData}}</div>
  <div @click=changeData> I am the parent component passing the modified data: {{mydata}}</div>
</template>
<script>
  export default{
    name:'Son',
    props:{
      fData:{
        type:String,
        default:''
      }
    }
    data(){
      mydata:this.fatherData
    },
    methods:{
     changeData(){
        this.mydata += ' Change data '
      }
    },
  }
</script>
0

4. $parent, $children access component instances directly

Subcomponents pass through-- > $parent Get Parent Component Instance The parent component passes through-- > $children get an array of subcomponent instances

Subcomponent-this. $parent can get the method of the parent component, the data of data and so on, and can be used and executed directly


<template>
  <div> I am the data of the parent component: {{fData}}</div>
  <div @click=changeData> I am the parent component passing the modified data: {{mydata}}</div>
</template>
<script>
  export default{
    name:'Son',
    props:{
      fData:{
        type:String,
        default:''
      }
    }
    data(){
      mydata:this.fatherData
    },
    methods:{
     changeData(){
        this.mydata += ' Change data '
      }
    },
  }
</script>
1

Parent Component--Obtains the instance of a child component, and the obtained instance is in the form of an array. this. $children [0] can obtain a component instance and call the component method and data


<template>
  <div> I am the data of the parent component: {{fData}}</div>
  <div @click=changeData> I am the parent component passing the modified data: {{mydata}}</div>
</template>
<script>
  export default{
    name:'Son',
    props:{
      fData:{
        type:String,
        default:''
      }
    }
    data(){
      mydata:this.fatherData
    },
    methods:{
     changeData(){
        this.mydata += ' Change data '
      }
    },
  }
</script>
2

5. $refs

ref is used to register reference information for an element or subcomponent. The reference information will be registered on the $refs object of the parent component.

The parent component uses $refs to get the component instance


<template>
  <div>
    <Son ref="son"></Son>
  </div>
</template>

<script>
import Son from './son.vue'

export default{
  name: 'father',
  components:{
    Son
  },
  mounted(){
    console.log(this.$refs.son) /* Component instance */
  }
}
</script>

6. provide/inject (provide/inject) multi-component or deep-level component communication

Detailed Explanation of provide/inject

Parent component injects data using provide Subcomponents use inject to use data

<template>
  <div> I am the data of the parent component: {{fData}}</div>
  <div @click=changeData> I am the parent component passing the modified data: {{mydata}}</div>
</template>
<script>
  export default{
    name:'Son',
    props:{
      fData:{
        type:String,
        default:''
      }
    }
    data(){
      mydata:this.fatherData
    },
    methods:{
     changeData(){
        this.mydata += ' Change data '
      }
    },
  }
</script>
4

So far, the provideName variable can be provided to all its sub-components, including great-grandchildren, grandchildren components, etc., and data can be obtained only by using inject


<template>
  <div> I am the data of the parent component: {{fData}}</div>
  <div @click=changeData> I am the parent component passing the modified data: {{mydata}}</div>
</template>
<script>
  export default{
    name:'Son',
    props:{
      fData:{
        type:String,
        default:''
      }
    }
    data(){
      mydata:this.fatherData
    },
    methods:{
     changeData(){
        this.mydata += ' Change data '
      }
    },
  }
</script>
5 The parent component does not need to know which component uses the data it provides Sub-attachments do not need to know where this data comes from

7. slot (slot-scope scope slot) child element-- > Parent element (similar to communication)

Used as a reusable template (which can be passed data) to replace the rendered elements In a subcomponent, just pass the data to the slot, just like you passed prop to component 1 Note: Parent slot receive is the outermost element and must have attributes slot-scope

Child element


<template>
  <div> I am the data of the parent component: {{fData}}</div>
  <div @click=changeData> I am the parent component passing the modified data: {{mydata}}</div>
</template>
<script>
  export default{
    name:'Son',
    props:{
      fData:{
        type:String,
        default:''
      }
    }
    data(){
      mydata:this.fatherData
    },
    methods:{
     changeData(){
        this.mydata += ' Change data '
      }
    },
  }
</script>
6

Parent element


<template>
  <div> I am the data of the parent component: {{fData}}</div>
  <div @click=changeData> I am the parent component passing the modified data: {{mydata}}</div>
</template>
<script>
  export default{
    name:'Son',
    props:{
      fData:{
        type:String,
        default:''
      }
    }
    data(){
      mydata:this.fatherData
    },
    methods:{
     changeData(){
        this.mydata += ' Change data '
      }
    },
  }
</script>
7

8. vuex Status Management

Equivalent to a warehouse of public data

Provide 1 method to manage warehouse data


import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

Summarize


Related articles: