Skip to content

Commit

Permalink
vue setWithPath(响应式对象, 路径, 新值)
Browse files Browse the repository at this point in the history
  • Loading branch information
realgeoffrey committed Sep 14, 2024
1 parent 5d7b03f commit 20157d0
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions 网站前端/Vue.js学习笔记/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2249,6 +2249,35 @@ Vue.use(MyPlugin, { /* 向MyPlugin传入的参数 */ })
在下次DOM更新循环结束之后执行延迟回调函数。
4. `Vue.set(响应式对象, 键/索引, 新值)`
- <details>
<summary>实现<code>setWithPath(响应式对象, 路径, 新值)</code></summary>
```js
function setWithPath(target, propertyPath, value, vm) {
if (Object.prototype.toString.call(target) !== "[object Object]" && Object.prototype.toString.call(target) !== "[object Array]") {
throw new Error("target仅支持Object和Array");
}
const pathArr = propertyPath.split("."); // propertyPath路径,以.分割(可改动实现)
const propertyName = pathArr.pop();
let finalTarget = target;
let preFinalTarget;
for (const key of pathArr) {
preFinalTarget = finalTarget;
finalTarget = finalTarget[key];
if (Object.prototype.toString.call(finalTarget) !== "[object Object]" && Object.prototype.toString.call(finalTarget) !== "[object Array]") { // 仅支持Object和Array。fixme:判断不是响应式对象
finalTarget = vm.$set(preFinalTarget, key, {});
}
}
vm.$set(finalTarget, propertyName, value);
}
setWithPath(this.a, "b.c.d", "value1", this);
```
</details>
5. `Vue.delete(响应式对象, 键/索引)`
6. `Vue.directive('自定义指令名'[, 钩子对象 或 带参数回调函数])`
Expand Down

0 comments on commit 20157d0

Please sign in to comment.