2-300行代码模拟vue实现
粉丝福利 : 关注VUE中文社区公众号,回复视频领取粉丝福利
vue-toy
npm install --save vue-toy
2-300行代码模拟vue实现。
Vue(options)
interface Options {
el: HTMLElement;
propsData?: Record<string, any>;
props?: string[];
name?: string;
data?: () => Record<string, any>;
methods?: Record<string, (e: Event) => void>;
computed?: Record<string, () => any>;
watch?: Record<string, (newValue: any, oldValue: any) => any>;
render: (h: typeof React.createElement) => React.ReactNode;
renderError?: (h: typeof React.createElement, error: Error) => React.ReactNode;
mounted?: () => void;
updated?: () => void;
destroyed?: () => void;
errorCaptured?: (e: Error, vm: React.ReactInstance) => void;
}
示例:
import Vue from "vue-toy";
new Vue({
el: document.getElementById("root"),
data() {
return {
msg: "hello vue toy"
};
},
render(h) {
return h("h1", null, this.msg);
}
});
注
:vue-toy的视图渲染使用的react
,所以render方法的使用同react#render
,如:
import Vue from "vue-toy";
import React from "react";
new Vue({
el: document.getElementById("root"),
data() {
return {
msg: "hello vue toy"
};
},
render() {
return <h1>{this.msg}</h1>
}
});
全局 API
Vue.component(ComponentOptions)
interface ComponentOptions {
props?: string[];
name?: string;
data?: () => Record<string, any>;
methods?: Record<string, (e: Event) => void>;
computed?: Record<string, () => any>;
watch?: Record<string, (newValue: any, oldValue: any) => any>;
render: (h: typeof React.createElement) => React.ReactNode;
renderError?: (h: typeof React.createElement, error: Error) => React.ReactNode;
mounted?: () => void;
updated?: () => void;
destroyed?: () => void;
errorCaptured?: (e: Error, vm: React.ReactInstance) => void;
}
示例:
const Hello = Vue.component({
props: ["msg"],
render(h){
return h('div', null, this.msg);
}
});