Seven ways for Vue components to communicate

Provide and inject(ancestors communicate with future generations)

    // in the parent component, define the values to be passed :(the same level as data)
    provide(){
      return{
         name:'Tom',}}Copy the code
	// In the sub-component, inject(the same as data) to receive, after receiving can be used as data
    inject: ['name']
Copy the code
Inject no matter how deep the child component is, it can be used if it has been provided in the previous ancestor componentCopy the code

2. Props

Parent component passes to child component with: data name =' data 'Copy the code
<template>
  <div>
      <Child :title='title'></Child>
  </div>
</template>
<script>
  import Child from './Child'
  
  export default{
      data(){
          return {
              title:'I'm the parent component's data'}},components:{
          Child
      }
  }
</script>
Copy the code
Props is used to receive in the child component, the same as dataCopy the code
// There are three clock reception modes, array, object, object + rule, here object + rule
props: {title: {type:String.// Type detection
      default:' '.// Set to the default value passed in
      required:true.// Whether it must be passed in. The default is false
      // For complex validation
      validator:funciont(value){
      	return value.length > 6}}}// Array mode
props: ['title']
// Object mode
props: {title:'String'
}
Copy the code

3.$emit (Child to parent)

Use $emit to emit events in child componentsCopy the code
// For example, click the event to trigger the child to parent operation
methods: {onClick(){
        // The first argument is the name of the event received by the parent component, followed by the payload argument
        this.$emit('titleChange'.this.title)
    }
}
Copy the code
The parent component is used with the @ event nameCopy the code
<Child @titleChange='titleChange'></Child>
...
methods: {// Parameters are the parameters passed by the child component
    titleChange(title){
        this.title = title; }}Copy the code

4.$ref (parent calls or accesses child methods and data)

There is no need to perform other operations on the sub-componentCopy the code
// Child.vue

<template>
<div class="child">
</div>
</template>

<script>
export default {
name: 'Child',
data () {
  return {
    title: 'I am the content of the child component'}},methods: {
  childAlert () {
    window.alert('I'm a popover inside a child component! ')}}}</script>

<style scoped>
</style>
Copy the code
The parent component needs ref=Copy the code

▲ If ref is used on a normal DOM element, it refers to the DOM element; if it is a child component, it refers to the component instance

// App.vue

<template>
  <div id="app">// we use ref here, and the name can be arbitrary<Child ref="childRef"/>
  </div>
</template>

<script>
import Child from './components/Child'

export default {
  name: 'App',
  data () {
    return{}},components: {
    Child
  },
  mounted () {
    // Access the title of the child component
    console.log(this.$refs.childRef.title)  // Output 'I am the content of a child component'
    // Call the child component's childAlert method
    this.$refs.childRef.childAlert()
  }
}
</script>

<style>
</style>
Copy the code

5. Event bus $bus

Method one: Use an empty VUE instance as the busCopy the code
//bus.js
import Vue from 'vue';
const bus = new Vue();
// Export a Vue instance named bus
export default bus;
Copy the code
/ / A component
<template>
  <div>
    <h1>I am component A</h1>
    <el-button @click="clickEve">To B</el-button>
  </div>
</template>

<script>
  // Start with bus.js
  import bus from ".. /.. /bus/bus";
  export default {
    name: "BusTest".data(){
      return{
        message:'A components'}},methods: {clickEve(){
          // this is $emit
        bus.$emit('getMessage'.this.message)
      }
    }
  }
</script>
Copy the code
/ / B component
<template>
  <div>
    <h2>I am B component</h2>
    <div>I can communicate with {{message}}</div>
  </div>
</template>

<script>
/ / the introduction of bus. Js
  import bus from ".. /.. /bus/bus";
  export default {
    name: "BusTest2".data(){
      return{
        message:' ',}},mounted() {
        // Call the bus method with the $on method
      bus.$on('getMessage'.data= >{
        // console.log(data)
        this.message = data
      })
    },
    // It needs to be destroyed
    beforDestory(){
        this.$off('getMessage')}}</script>
Copy the code
Method 2: define $bus in vue prototype, global useCopy the code
//mian.js
onst bus = new Vue()
Vue.prototype.$bus = bus
// Other components need to pass in data directly $bus.***, use the same
Copy the code
Method 3: Use the vue-bus plug-inCopy the code
/ / installation
npm install vue-bus --save
//main.js
import VueBus from 'vue-bus';// Central event bus
Vue.use(VueBus)
Copy the code

6.$parent

// You can use $parent in a child to access the parent's data, methods, etc
mounted(){
	// Get the data of the parent component
    this.msg = this.$parent.msg
    // Call the parent component's methods
    this.$paren.meth()
}
Copy the code

7.Observable

//strore.js
// State data
export let store = Vue.observable({
    count:0,})// The processing method
export let mutations={
    setCount(count){
        store.count = count
    }
}
Copy the code
// The user only needs to import
import {mutations,store} from './store.js'
Copy the code

8.Vuex