This is the 17th day of my participation in the August Challenge

Binding components to native events (.native)

To listen for a native event directly on the root element of a component, use the.native modifier of v-ON.

<child content="hello VUE" @click="handleClick"></child>

Native click events are invalid if not written. The reason is that a child component’s click event is a native event, whereas a parent component’s click event is a custom event.

Values passed between non-parent and child components

When there is very complex data transfer in the project (mainly between the same level components need to transfer data, if simply relying on layer by layer, the project may become complicated), so Vue framework alone cannot solve the complex data transfer. At this point we need to introduce some tools or design patterns to solve the complex data transfer between components in Vue. VUE provides two solutions for data transfer between non-parent and child components:

  • Vue officially provides a data layer framework – Vuex;
  • Publish subscribe pattern (also known as Bus mechanism /Bus/ observer pattern).

When the communication data is relatively simple, the second solution can be used. When the project is large, Vuex can be used.

Here we mainly introduce the second mode, which is divided into three steps:

1. Create an event bus.

2. Use $emit to send the value;

$on (mounted); $on (mounted);

Concrete implementation:

Scenario requirement: Click component A to change the value of component B and vice versa. (For the convenience of the experiment, take the same component as an example);

Method implementation: first to achieve component rendering, and then click to display data, and finally realize the value of brother components.

Prototype. Bus = new vue () var child = {// The parent component passes values according to the unidirectional data flow rule data: function() { return { childContent: this.content } }, props: { content: String }, template: '<div @click="handleClick">{{childContent}}</div>', methods: { handleClick: $emit('change', this.childContent)} // If (echo) {this.bus.$emit('change', this.childContent)} Function () {this.bus.$on('change',function(MSG) {_this.childContent = MSG)}}Copy the code

Key points:

  • parsingthis.bus.$emit('change', this.content):

Bus = new Vue (); bus = new Vue (); bus = new Vue ()

  • parsingVue .prototype.bus:

Vue’s Prototype has a bus property mounted that points to an instance of Vue. Later, whenever new.Vue is called or a component is created, each component will have the bus property (why? Since every Vue instance and component is created from the Vue class, a bus attribute is mounted in Vue prototype that points to the same Vue instance.

  • Since both components are loaded almost at the same time, event subscriptions occur$onOn themoutedIn the can.