Common projects use event cars, common Vue instances to pass data

There are two ways to write event cars, which are described below

  • Use emit emit custom events and emit Emit custom events and emit emit custom events and on to listen for custom events
  • $off Destruction event

1. The first method (create a public file)

Create public files in SRC folder

1.  // Create a public js file (event car), which is mainly used to pass information
1.  / / introduction of vue. Js
1.  import Vue from 'vue';
1.  // Create an empty vue instance
1.  var event = new Vue();
1.
1.  export default event;
Copy the code

Home. Vue file


<template>
  <div id="home">
    <h2>This is the home page</h2>
    <h3>{{list}}</h3>
    <h5>{{mymsg}}</h5>
 
    <button @click="biu">launch</button>
  </div>
</template>
<script>
// introduce information where it needs to be passed
import bus from '.. /eventBus.js'
export default{
  data(){
    return{
      list: ['Less desire tone'.'orthotonic'.Uncle tone].mymsg:' '}},methods: {
    biu(){
      // Emits a custom event to pass information
      console.log(bus);
      bus.$emit('biulist'.this.list)
    }
  },
  mounted() {// The hook function that fires when the component is mounted
    // Receive information
    bus.$on('msg'.val= >{
      this.mymsg = val
    })
  },
}
</script>
Copy the code

The second way is to mount the prototype directly

Define a new object in main.js and mount it to the Vue prototype

Vue.prototype.$bus=new Vue();
Copy the code

The home page

1.  methods: {
1.  msg() {
1.  $emit sends data to carry data
1.  this.$bus.$emit("A", {
1.  name: "Zhang".1.  age: 20
1.  });
1.  }
1.  }
Copy the code

Prodct.vue is a page unrelated to the home page

 mounted() {
//$on/mounted
this.$bus.$on("A".function(res) {
console.log(res);
});
}
Copy the code
Choose one of two ways! Public _ number front-end honest people, you can chat with exchange learning oh!Copy the code