Communication between the components VueJS

Component is VueJSone of the most powerful features, by the combination of components, applications like pushing a combination of building blocks. Between the various components are independent, which means that data between different components can not be shared, so that the communication between the components is particularly important, the article describes the communication between the components in detail VueJS

Component Diagram

Here Insert Picture Description
From the figure we can clearly understand the relationship between the components. We need to choose a different way of communication between the different components for

props/$emit`

  • propsAttribute is a parent component by way of the communication subassembly parent component by proppassing, through the sub-assembly propsStatement
    Here Insert Picture Description
  • Sub-assemblies, components can be passed to the parent value through custom events $emitpassed way, sub-components distribution events, parent component listens for events
    Here Insert Picture Description

$ Emit / $ on (event bus)

Communication between components by way of a bus event we can achieve a relationship or no relationship, if you encounter more complex projects, it is recommended to use Vuex to solve

We can new Vue()an empty Vueinstance of the bus as a whole project, distribute and monitor the realization of events

const bus = new Vue()
Vue.prototype.$bus = bus

Throughout the project components, can be used this.$bus.$emit()to distribute events, use this.$bus.$on()to listen for events
Here Insert Picture Description

$attrs/$listeners

  • $attrs: It contains the parent scope is not propbound to the identified characteristics (style / class excluded). When a component is no proptime, there will bind all contain the parent scope, and can be v-bind="$attrs"passed internal components
  • $listeners: Contains the parent scope of the v-onevent listener, it can be v-on="$listeners"an internal incoming components
    Here Insert Picture Description

The results of printing

Here Insert Picture Description

provide/inject

An ancestor component used provideto inject a dependency to future assembly component used in the offspring injectto receive variables ancestor component provides.
Here Insert Picture Description

$parent/$children/$ref

  • $ Ref: If used in a generic DOM element reference point is the DOM elements, if used in the subassembly, is a reference to a component instance
  • $parent/ $children: Access component instance Sons
    Here Insert Picture Description

Print results

Here Insert Picture Description

Vuex

Released four original articles · won praise 0 · Views 70

Guess you like

Origin blog.csdn.net/k19970320j/article/details/104389995