Appearance
添加生命周期方法
本节目标:理解“添加生命周期方法”的核心思路,并能把它用于实际开发或面试表达。
import { initMixin } from "./init";
import { lifeCycleMixin } from "./lifeCycle";
import { renderMixin } from "./render";
// vue要如何实现,原型模式,所有的功能都通过原型扩展的方式来添加
function Vue(options){
this._init(options); //实现vue的初始化功能
}
initMixin(Vue);
renderMixin(Vue);
lifeCycleMixin(Vue);
//导出vue给别人使用
export default Vue;Vue.prototype.$mount = function (el) {
const vm = this;
const opts = vm.$options;
el = document.querySelector(el); //获取真实的元素
vm.$el = el; //页面真实元素
if (!opts.render) {
//模板编译
let template = opts.template;
if (!template) {
template = el.outerHTML;
}
let render = compileToFunction(template)
opts.render = render;
}
mountComponent(vm)
}_v vnode
_c createElement
_s stringify//导出vue给别人使用
export default Vue;import { isObject } from "./utils"
import { createElement, createText } from "./vdom"
export function renderMixin(Vue) {
Vue.prototype._c = function () { // createElement创建元素型的节点
const vm = this;
return createElement(vm, ...arguments)
}
Vue.prototype._v = function (text) { //创建文本的虚拟节点
const vm = this;
return createText(vm, text); //描述虚拟节点是属于哪个实例的
}
Vue.prototype._s = function (val) { // JSON.stingfiy()
if (isObject(val)) return JSON.stringify(val);
return val;
}
Vue.prototype._render = function () {
const vm = this; // vm中有所有的数据
vm.xxx => vm._data.xxx
let { render } = vm.$options;
let vnode = render.call(vm);
return vnode;
}
}创建src/compiler/generate.js,
创建方法