Vue3 中使用 Proxy 来实现响应式数据变化。
简单的组件仍然可以采用 OptionsAPI 进行编写(但是在 Vue3 中基本不在使用)
compositionAPI 在复杂的逻辑中有着明显的优势~
this
指向不明确问题tree-shaking
更加友好,代码也更容易压缩。reactivity
模块中就包含了很多我们经常使用到的 API
例如:computed
、 reactive
, ref
, effect
等。
其中:
reactive
让数据变成响应式effect
副作用:数据变化后可以让 effect 重新执行
watch
、computed
都是基于 effect 来实现的<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script type="module">
import { reactive, effect } from '<https://unpkg.com/vue@3/dist/vue.esm-browser.js>'
const state = reactive({ name: "lance", age: 30 });
effect(() => {
app.innerHTML = `姓名${state.name} 年龄${state.age}`;
});
setTimeout(() => {
state.age++; // 数据变化后 effect 会再次重新执行
}, 1000)
</script>
</body>
</html>
reactive 用 Proxy 来代理对象的所有属性访问,包括对对象新增属性、删除属性等的拦截。