preface

If you want to have a better understanding of value transmission from non-parent components, you should first understand the thinking logic of value transmission from parent to child, so that you can better understand the value transmission from non-parent components.

Non-parent component value passing (sibling component value passing)

  • The first thing to understand about non-parent component passing is to understand$emit$on , $emit(event,data)There are two parameters in there: the first parameter is the type of event that was fired, the second value is the parameter that triggered the event,$on(event, callFn(data))The same$onThere are also two parameters, the first parameter is the bound event type, the second value is the bound event corresponding to the callback function, insidedataThe value is$emitThe value passed from.

1. Define a BUS (an instance of vUE that receives and fires events) as follows:

       import Vue from 'vue'
       export default new Vue()
Copy the code

2. First introduce the component to the page

<template>
  <div class="home">
      <childrenOne></childrenOne> 
      <children></children>
      
  </div>
</template>

<script>
// Introduce public pages
import children from './children.vue'
import childrenOne from './childrenOne.vue'
export default {
  name: 'Home'.data(){},
  components: {/ / register
    children,
    childrenOne
  }
}
</script>

Copy the code

3. Pass the data into an intermediate variable (BUS) in the childOne component as follows

<template>
    <div>
        $emit{{namea}}
    </div>
</template>
<script>
import bus from '.. /utli/bus'
export default {
    data(){
        return{
            namea:"Who am I?".listone:'3332113221'}},created() {
    // Pass the value into the bus
        bus.$emit("woshishi".this.namea)
    },
}
</script>
<style lang="less"></style>
Copy the code

4. Use $on in another component to listen for values in bus intermediate variables and display them on the page

<template>
    <div>
        $on{{namea}}
    </div>
</template>
<script>
import bus from '.. /utli/bus'
export default {
    data(){
        return{
            namea:"wss"}},created() {
        bus.$on("woshishi".(val) = >{
            this.namea = val
        })
    },
}
</script>
<style lang="less">
    
</style>
Copy the code