This article brings you the content is about the Vue.js component library Event System design process (code), there is a certain reference value, the need for friends can refer to, I hope to help you.
Let's take Input-number as an example:
@ is a shorthand for the v-on instruction to bind the event listener:
<inputnumber @on-change= "Change": max= ": min=" 1 "v-model=" value1 "></InputNumber>
When we use components, we register an 自定义
event:
Methods: {Change (v) { Console.log (v) }}
The way it is triggered inside a component is also simple:
Called the
$emit
To trigger an event on the current instance named
on-change
this. $emit (' On-change ', Val);
The idea is that if the InputNumber
outer layer is nested FormItem
inside a component, the invocation of the event is similar, but there is a hypothesis:
Nested relationships, may have multiple-level parent-child
Like element
and iview
more designed one mixins
, it provides a way to:dispatch
It takes 3
a parameter:
ComponentName Component Name
EventName Custom Event Name
Parameters passed by the params event
Dispatch (ComponentName, eventName, params) {}
For example input-number
, many of these form-embedded components will be designed and FormItem
interacted with:
This.dispatch (' FormItem ', ' On-form-change ', Val);
FormItem
When designing components, we note:
Export Default { name: ' FormItem '}
Then register a custom event in the same way:
<form-item @on-form-change= "test" ></Form-item>
Let's take a look inside the dispatch function:
The idea is to find the parent element on one layer at a level:
var parent = this. $parent | | this. $root;
Gets the name of the parent component:
var name = parent. $options. Name;
Start Loop judgment:
while (parent && (!name | | name!== componentname)) { //...}
For example, the above input-number
internal call dispatch, passed the parameter, is always looking for name
the parent element to FormItem
the
Inside the while:
Then look for its parent example and get the name
Parent = parent. $parent; if (parent) { name = parent. $options. Name;}
In the End If you find:
Is the same as triggering a custom event at the beginning: $emit
if (parent) {parent. $emit. Apply (parent, [Eventname].concat (params));}