蓝狮注册登陆为什么 Vue2 this 能够直接获取到 data 和 methods ?

在平时使用vue来开发项目的时候,对于下面这一段代码,我们可能每天都会见到:

const vm = new Vue({
data: {
name: ‘我是pino’,
},
methods: {
print(){
console.log(this.name);
}
},
});
console.log(vm.name); // 我是pino蓝狮注册登陆
vm.print(); // 我是pino
但是我们自己实现一个构造函数却实现不了这种效果呢?

function Super(options){}
const p = new Super({
data: {
name: ‘pino’
},
methods: {
print(){
console.log(this.name);
}
}
});
console.log(p.name); // undefined
p.print(); // p.print is not a function
那么vue2中是怎么实现这种调用方式的呢?

首先可以找到vue2的入口文件:

src/core/instance/index

function Vue (options) {
if (process.env.NODE_ENV !== ‘production’ &&
!(this instanceof Vue)
) {
warn(‘Vue is a constructor and should be called with the new keyword’)蓝狮注册开户
}
this._init(options)
}
// 初始化操作是在这个函数完成的
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
export default Vue
接下来看initMixin文件中是如何实现的:

export function initMixin (Vue: Class) {
Vue.prototype._init = function (options?: Object) {
const vm: Component = this
// a uid
vm._uid = uid++
let startTag, endTag
/* istanbul ignore if / if (process.env.NODE_ENV !== ‘production’ && config.performance && mark) { startTag = vue-perf-start:${vm._uid} endTag = vue-perf-end:${vm._uid} mark(startTag) } // a flag to avoid this being observed vm._isVue = true // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options) } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ) } / istanbul ignore else */
if (process.env.NODE_ENV !== ‘production’) {
initProxy(vm)
} else {
vm._renderProxy = vm
}
// expose real self
vm._self = vm
initLifecycle(vm)
initEvents(vm)
initRender(vm)
callHook(vm, ‘beforeCreate’)
initInjections(vm) // resolve injections before data/props

// 初始化data/methods…
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, ‘created’)
}
}

0 Comments
Leave a Reply