Home Web Front-end JS Tutorial Detailed explanation of the use of vue event mechanism

Detailed explanation of the use of vue event mechanism

Apr 27, 2018 pm 02:14 PM
use mechanism Detailed explanation

这次给大家带来vue事件机制使用详解,vue事件机制使用的注意事项有哪些,下面就是实战案例,一起来看一下。

上一章没什么经验。直接写了组件机制。感觉涉及到的东西非常的多,不是很方便讲。今天看了下vue的关于事件的机制。有一些些体会。写出来。大家一起纠正,分享。源码都是基于最新的Vue.js v2.3.0。下面我们来看看vue中的事件机制:
老样子还是先上一段贯穿全局的代码,常见的事件机制demo都会包含在这段代码中:

<p id="app">
 <p id="test1" @click="click1">click1</p>
 <p id="test2" @click.stop="click2">click2</p>
 <my-component v-on:click.native="nativeclick" v-on:componenton="parentOn">
 </my-component>
</p>
</body>
<script src="vue.js"></script>
<script type="text/javascript">
var Child = {
 template: '<p>A custom component!</p>'
} 
Vue.component('my-component', {
 name: 'my-component',
 template: '<p>A custom component!<p @click.stop="toParent">test click</p></p>',
 components: {
 Child:Child
 },
 created(){
 console.log(this);
 },
 methods: {
 toParent(){
  this.$emit('componenton','toParent')
 }
 },
 mounted(){
 console.log(this);
 }
})
 new Vue({
 el: '#app',
 data: function () {
 return {
  heihei:{name:3333},
  a:1
 }
 },
 components: {
 Child:Child
 },
 methods: {
 click1(){
  alert('click1')
 },
 click2(){
  alert('click2')
 },
 nativeclick(){
  alert('nativeclick')
 },
 parentOn(value){
  alert(value)
 }
 }
})
</script>
Copy after login

上面的demo中一共有四个事件。基本涵盖了vue中最经典的事件的四种情况

普通html元素上的事件

好吧。想想我们还是一个个来看。如果懂vue组件相关的机制会更容易懂。那么首先我们看看最简单的第一、二个(两个事件只差了个修饰符):

<p id="test1" @click="click1">click1</p>
Copy after login

这是简单到不能在简单的一个点击事件。

我们来看看建立这么一个简单的点击事件,vue中发生了什么。

1:new Vue()中调用了initState(vue):看代码

function initState (vm) {
 vm._watchers = [];
 var opts = vm.$options;
 if (opts.props) { initProps(vm, opts.props); }
 if (opts.methods) { initMethods(vm, opts.methods); }//初始化事件
 if (opts.data) {
 initData(vm);
 } else {
 observe(vm._data = {}, true /* asRootData */);
 }
 if (opts.computed) { initComputed(vm, opts.computed); }
 if (opts.watch) { initWatch(vm, opts.watch); }
}
//接着看看initMethods
function initMethods (vm, methods) {
 var props = vm.$options.props;
 for (var key in methods) {
 vm[key] = methods[key] == null ? noop : bind(methods[key], vm);//调用了bind方法,我们再看看bind
 {
  if (methods[key] == null) {
  warn(
   "method \"" + key + "\" has an undefined value in the component definition. " +
   "Did you reference the function correctly?",
   vm
  );
  }
  if (props && hasOwn(props, key)) {
  warn(
   ("method \"" + key + "\" has already been defined as a prop."),
   vm
  );
  }
 }
 }
}
//我们接着看看bind
function bind (fn, ctx) {
 function boundFn (a) {
 var l = arguments.length;
 return l
  ? l > 1
  ? fn.apply(ctx, arguments)//通过返回函数修饰了事件的回调函数。绑定了事件回调函数的this。并且让参数自定义。更加的灵活
  : fn.call(ctx, a)
  : fn.call(ctx)
 }
 // record original fn length
 boundFn._length = fn.length;
 return boundFn
}
Copy after login

总的来说。vue初始化的时候,将method中的方法代理到vue[key]的同时修饰了事件的回调函数。绑定了作用域。

2:vue进入compile环节需要将该p变成ast(抽象语法树)。当编译到该p时经过核心函数genHandler:

function genHandler (
 name,
 handler
) {
 if (!handler) {
 return 'function(){}'
 }
 if (Array.isArray(handler)) {
 return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]")
 }
 var isMethodPath = simplePathRE.test(handler.value);
 var isFunctionExpression = fnExpRE.test(handler.value);
 if (!handler.modifiers) {
 return isMethodPath || isFunctionExpression//假如没有修饰符。直接返回回调函数
  ? handler.value
  : ("function($event){" + (handler.value) + "}") // inline statement
 } else {
 var code = '';
 var genModifierCode = '';
 var keys = [];
 for (var key in handler.modifiers) {
  if (modifierCode[key]) {
  genModifierCode += modifierCode[key];//处理修饰符数组,例如.stop就在回调函数里加入event.stopPropagation()再返回。实现修饰的目的
  // left/right
  if (keyCodes[key]) {
   keys.push(key);
  }
  } else {
  keys.push(key);
  }
 }
 if (keys.length) {
  code += genKeyFilter(keys);
 }
 // Make sure modifiers like prevent and stop get executed after key filtering
 if (genModifierCode) {
  code += genModifierCode;
 }
 var handlerCode = isMethodPath
  ? handler.value + '($event)'
  : isFunctionExpression
  ? ("(" + (handler.value) + ")($event)")
  : handler.value;
 return ("function($event){" + code + handlerCode + "}")
 }
}
Copy after login

genHandler函数简单明了,如果事件函数有修饰符。就处理完修饰符,添加修饰符对应的函数语句。再返回。这个过程还会单独对native修饰符做特殊处理。这个等会说。compile完后自然就render。我们看看render函数中这块区域长什么样子:

复制代码 代码如下:


_c('p',{attrs:{"id":"test1"},on:{"click":click1}},[_v("click1")]),_v(" "),_c('p',{attrs:{"id":"test2"},on:{"click":function($event){$event.stopPropagation();click2($event)}}}

一目了然。最后在虚拟dom-》真实dom的时候。会调用核心函数:

function add$1 (
 event,
 handler,
 once$$1,
 capture,
 passive
) {
 if (once$$1) {
 var oldHandler = handler;
 var _target = target$1; // save current target element in closure
 handler = function (ev) {
  var res = arguments.length === 1
  ? oldHandler(ev)
  : oldHandler.apply(null, arguments);
  if (res !== null) {
  remove$2(event, handler, capture, _target);
  }
 };
 }
 target$1.addEventListener(
 event,
 handler,
 supportsPassive
  ? { capture: capture, passive: passive }//此处绑定点击事件
  : capture
 );
}
Copy after login

组件上的事件

好了下面就是接下来的组件上的点击事件了。可以预感到他走的和普通的html元素应该是不同的道路。事实也是如此:

<my-component v-on:click.native="nativeclick" v-on:componenton="parentOn">
 </my-component>
Copy after login

最简单的一个例子。两个事件的区别就是一个有.native的修饰符。我们来看看官方.native的作用:在原生dom上绑定事件。好吧。很简单。我们跟随源码看看有何不同。这里可以往回看看我少的可怜的上一章组件机制。vue中的组件都是扩展的vue的一个新实例。在compile结束的时候你还是可以发现他也是类似的一个样子。如下图:

复制代码 代码如下:

_c('my-component',{on:{"componenton":parentOn},nativeOn:{"click":function($event){nativeclick($event)}}

可以看到加了.native修饰符的会被放入nativeOn的数组中。等待后续特殊处理。等不及了。我们直接来看看特殊处理。render函数在执行时。如果遇到组件。看过上一章的可以知道。会执行

function createComponent (
 Ctor,
 data,
 context,
 children,
 tag
) {
 if (isUndef(Ctor)) {
 return
 }
 var baseCtor = context.$options._base;
 // plain options object: turn it into a constructor
 if (isObject(Ctor)) {
 Ctor = baseCtor.extend(Ctor);
 }
 // if at this stage it's not a constructor or an async component factory,
 // reject.
 if (typeof Ctor !== 'function') {
 {
  warn(("Invalid Component definition: " + (String(Ctor))), context);
 }
 return
 }
 // async component
 if (isUndef(Ctor.cid)) {
 Ctor = resolveAsyncComponent(Ctor, baseCtor, context);
 if (Ctor === undefined) {
  // return nothing if this is indeed an async component
  // wait for the callback to trigger parent update.
  return
 }
 }
 // resolve constructor options in case global mixins are applied after
 // component constructor creation
 resolveConstructorOptions(Ctor);
 data = data || {};
 // transform component v-model data into props & events
 if (isDef(data.model)) {
 transformModel(Ctor.options, data);
 }
 // extract props
 var propsData = extractPropsFromVNodeData(data, Ctor, tag);
 // functional component
 if (isTrue(Ctor.options.functional)) {
 return createFunctionalComponent(Ctor, propsData, data, context, children)
 }
 // extract listeners, since these needs to be treated as
 // child component listeners instead of DOM listeners
 var listeners = data.on;//listeners缓存data.on的函数。这里就是componenton事件
 // replace with listeners with .native modifier
 data.on = data.nativeOn;//正常的data.on会被native修饰符的事件所替换
 if (isTrue(Ctor.options.abstract)) {
 // abstract components do not keep anything
 // other than props & listeners
 data = {};
 }
 // merge component management hooks onto the placeholder node
 mergeHooks(data);
 // return a placeholder vnode
 var name = Ctor.options.name || tag;
 var vnode = new VNode(
 ("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')),
 data, undefined, undefined, undefined, context,
 { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }
 );
 return vnode
}
Copy after login

整段代码关于事件核心操作:

var listeners = data.on;//listeners缓存data.on的函数。这里就是componenton事件
// replace with listeners with .native modifier
data.on = data.nativeOn;//正常的data.on会被native修饰符的事件所替换
Copy after login

经过这两句话。.native修饰符的事件会被放在data.on上面。接下来data.on上的事件(这里就是nativeclick)会按普通的html事件往下走。最后执行target.add('',''')挂上原生的事件。而先前的data.on上的被缓存在listeneners的事件就没着么愉快了。接下来他会在组件init的时候。它会进入一下分支:

function initEvents (vm) {
 vm._events = Object.create(null);
 vm._hasHookEvent = false;
 // init parent attached events
 var listeners = vm.$options._parentListeners;
 if (listeners) {
 updateComponentListeners(vm, listeners);
 }
}
function updateComponentListeners (
 vm,
 listeners,
 oldListeners
) {
 target = vm;
 updateListeners(listeners, oldListeners || {}, add, remove$1, vm);
}
function add (event, fn, once$$1) {
 if (once$$1) {
 target.$once(event, fn);
 } else {
 target.$on(event, fn);
 }
}
Copy after login

发现组件上的没有.native的修饰符调用的是$on方法。这个好熟悉。进入到$on,$emit大致想到是一个典型的观察者模式的事件。看看相关$on,$emit代码。我加点注解:

Vue.prototype.$on = function (event, fn) {
 var this$1 = this;
 var vm = this;
 if (Array.isArray(event)) {
  for (var i = 0, l = event.length; i < l; i++) {
  this$1.$on(event[i], fn);
  }
 } else {
  (vm._events[event] || (vm._events[event] = [])).push(fn);//存入事件
  // optimize hook:event cost by using a boolean flag marked at registration
  // instead of a hash lookup
  if (hookRE.test(event)) {
  vm._hasHookEvent = true;
  }
 }
 return vm
 };
Vue.prototype.$emit = function (event) {
 var vm = this;
 console.log(vm);
 {
  var lowerCaseEvent = event.toLowerCase();
  if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {
  tip(
   "Event \"" + lowerCaseEvent + "\" is emitted in component " +
   (formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " +
   "Note that HTML attributes are case-insensitive and you cannot use " +
   "v-on to listen to camelCase events when using in-DOM templates. " +
   "You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"."
  );
  }
 }
 var cbs = vm._events[event];
 console.log(cbs);
 if (cbs) {
  cbs = cbs.length > 1 ? toArray(cbs) : cbs;
  var args = toArray(arguments, 1);
  for (var i = 0, l = cbs.length; i < l; i++) {
  cbs[i].apply(vm, args);//当emit的时候调用该事件。注意上面说的vue在初始化的守候。用bind修饰了事件函数。所以组件上挂载的事件都是在父作用域中的
  }
 }
 return vm
 };
Copy after login

看了上面的on,emit用法下面这个demo也就瞬间秒解了(一个经常用的非父子组件通信):

var bus = new Vue()
// 触发组件 A 中的事件
bus.$emit('id-selected', 1)
// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
 // ...
})
Copy after login

是不是豁然开朗。

又到了愉快的总结时间了。segementfault的编辑器真难用。内容多就卡。哎。烦。卡的时间够看好多肥皂剧了。

总的来说。vue对于事件有两个底层的处理逻辑。

1:普通html元素和在组件上挂了.native修饰符的事件。最终EventTarget.addEventListener() 挂载事件

2:组件上的,vue实例上的事件会调用原型上的$on,$emit(包括一些其他api $off,$once等等)

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

jQuery中使用for循环var与使用let有哪些区别

jquery layui弹出层使用详解

The above is the detailed content of Detailed explanation of the use of vue event mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Mar 10, 2024 pm 04:34 PM

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

See all articles