Eight Ways of Building Communication in vue

  • 2021-11-24 00:31:43
  • OfStack

Directory 1. Component Communication 1, props Parent-- > Subcomponent Communication 2, $emit Subcomponent-- > Parent component delivery 3, bus (event bus) sibling component communication 4, $parent, $children direct access component instance 5, $refs6, provide/inject (provide/inject) multi-component or deep-level component communication 7, slot (slot-scope scope slot) child elements-- > Parent element (similar to communication) 8, vuex state management

1. Component communication

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>

Subcomponent props The accepted parameter name is the same as the property 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 Vue One-way data flow mechanism, if you directly modify the value of the parent component, it will be "polluted". ( props Is one-way bound (read-only property): when the property of the parent component changes, it will be passed to the child component, but not the other way around)

The error message is: vue communication error using prop: Avoid mutating a prop directly since the value will be overwritten 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 the change 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, receives 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

provide/inject Detailed explanation

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 provideName This variable can be provided to all its subcomponents, including great-grandchildren, grandchildren, etc., and the 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 will prop Pass to Component 1 Sample Note: The parent slot receives 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: {
  }
})

Related articles: