上一章没什么经验。直接写了组件机制。感觉涉及到的东西非常的多,不是很方便讲。今天看了下vue的关于事件的机制。有一些些体会。写出来。大家一起纠正,分享。源码都是基于最新的Vue.js v2.3.0。下面我们来看看vue中的事件机制:
老样子还是先上一段贯穿全局的代码,常见的事件机制demo都会包含在这段代码中:
<div id="app">
<div id="test1" @click="click1">click1</div>
<div id="test2" @click.stop="click2">click2</div>
<my-component v-on:click.native="nativeclick" v-on:componenton="parentOn">
</my-component>
</div>
</body>
<script src="vue.js"></script>
<script type="text/javascript">
var Child = {
template: '<div>A custom component!</div>'
}
Vue.component('my-component', {
name: 'my-component',
template: '<div>A custom component!<div @click.stop="toParent">test click</div></div>',
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>
上面的demo中一共有四个事件。基本涵盖了vue中最经典的事件的四种情况
普通html元素上的事件
好吧。想想我们还是一个个来看。如果懂vue组件相关的机制会更容易懂。那么首先我们看看最简单的第一、二个(两个事件只差了个修饰符):
<div id="test1" @click="click1">click1</div>
这是简单到不能在简单的一个点击事件。
我们来看看建立这么一个简单的点击事件,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
}
内容版权声明:除非注明,否则皆为本站原创文章。
