原生加数组实现vue
使用原生 JavaScript 和数组实现 Vue 的核心功能
Vue 的核心功能包括数据响应式、模板渲染和指令绑定。通过原生 JavaScript 和数组可以模拟部分功能,以下是一个简化版的实现方式。
数据响应式实现
使用 Object.defineProperty 或 Proxy 监听数据变化,并触发更新逻辑。

const data = {
message: "Hello Vue",
items: ["Item 1", "Item 2", "Item 3"]
};
function observe(data) {
if (!data || typeof data !== "object") return;
Object.keys(data).forEach(key => {
let value = data[key];
Object.defineProperty(data, key, {
get() {
return value;
},
set(newValue) {
if (newValue !== value) {
value = newValue;
updateView(); // 数据变化时更新视图
}
}
});
});
}
observe(data);
模板渲染
通过 DOM 操作实现数据绑定和渲染。

function updateView() {
const app = document.getElementById("app");
app.innerHTML = `
<div>
<p>{{ message }}</p>
<ul>
${data.items.map(item => `<li>${item}</li>`).join("")}
</ul>
</div>
`;
}
updateView();
指令绑定(v-model)
监听输入框变化并更新数据。
const input = document.createElement("input");
input.setAttribute("type", "text");
input.addEventListener("input", (e) => {
data.message = e.target.value;
});
document.body.appendChild(input);
数组方法监听
Vue 通过重写数组方法(如 push、pop)实现响应式监听。
const arrayProto = Array.prototype;
const arrayMethods = Object.create(arrayProto);
["push", "pop", "shift", "unshift", "splice"].forEach(method => {
const original = arrayProto[method];
arrayMethods[method] = function(...args) {
const result = original.apply(this, args);
updateView(); // 数组变化时更新视图
return result;
};
});
data.items.__proto__ = arrayMethods;
完整示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue-like Implementation</title>
</head>
<body>
<div id="app"></div>
<input type="text" id="input">
<script>
const data = {
message: "Hello Vue",
items: ["Item 1", "Item 2", "Item 3"]
};
// 数据监听
function observe(data) {
if (!data || typeof data !== "object") return;
Object.keys(data).forEach(key => {
let value = data[key];
Object.defineProperty(data, key, {
get() {
return value;
},
set(newValue) {
if (newValue !== value) {
value = newValue;
updateView();
}
}
});
});
}
// 数组方法劫持
const arrayProto = Array.prototype;
const arrayMethods = Object.create(arrayProto);
["push", "pop", "shift", "unshift", "splice"].forEach(method => {
const original = arrayProto[method];
arrayMethods[method] = function(...args) {
const result = original.apply(this, args);
updateView();
return result;
};
});
data.items.__proto__ = arrayMethods;
// 视图更新
function updateView() {
const app = document.getElementById("app");
app.innerHTML = `
<div>
<p>${data.message}</p>
<ul>
${data.items.map(item => `<li>${item}</li>`).join("")}
</ul>
</div>
`;
}
// 初始化
observe(data);
updateView();
// v-model 模拟
document.getElementById("input").addEventListener("input", (e) => {
data.message = e.target.value;
});
</script>
</body>
</html>
注意事项
- 此实现仅为简化版,Vue 实际源码更复杂,包含虚拟 DOM、依赖收集等机制。
- 现代 Vue 3 使用
Proxy代替Object.defineProperty,支持深层监听。 - 数组监听需手动劫持方法,Vue 内部通过
__ob__标记实现。
此方法可用于理解 Vue 基本原理,实际开发建议直接使用 Vue 框架。






