Vue source code analysis (2) initproxy initialization proxy

Official account Life code 2021-05-03 14:43:41
vue source code analysis initproxy


Vue The source code parsing ( Two )initProxy Initialize agent

stay src/core/instance/proxy.js To find the source code

makeMap,allowedGlobals

Let's take a look first makeMap This method , What has been done :

/*makeMap function , str The parameter is the accepted string , expectsLowerCase Does the parameter need lowercase */
function makeMap(str, expectsLowerCase ) {
/* Create an object */
var map = Object.create(null);
/* Split a string into arrays */
var list = str.split(',');
/* Traversing an array */
for (var i = 0; i < list.length; i++) {
/* Each one key The corresponding value is set to true*/
map[list[i]] = true;
}
/* Eventually return , According to the parameter setting, whether the case needs to be converted */
return expectsLowerCase
? function (val) {
return map[val.toLowerCase()];
}
: function (val) {
return map[val];
}
}
 Copy code 

And then give some js The built-in global method does the corresponding processing :

var allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
);
 Copy code 

makeMap All the functions need to do is to make these global API In the form of ,

{
Infinity:true,
undefined:true
}
 Copy code 

isNative

You can learn how the source code detects whether it supports native methods

export function isNative (Ctor: any): boolean {
return typeof Ctor === 'function' && /native code/.test(Ctor.toString())
}
 Copy code 

warnNonPresent

The idea of this method is that it doesn't exist , Undefined properties , Method is used to warn , Let's take a look at an example :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="../vue.js"></script>
<div id="app">
<p>
{{msg}}
</p>
</div>
<script>
const vm = new Vue({
el: '#app',
})
console.log(vm)
</script>
</body>
</html>
 Copy code 

The above example is used directly in the magic board msg Variable , But he wasn't there data In the definition of , here warnNonPresent The warning will be handled, as shown in the figure

warnReservedPrefix

Source code is as follows :

const warnReservedPrefix = (target, key) => {
warn(
`Property "${key}" must be accessed with "$data.${key}" because ` +
'properties starting with "$" or "_" are not proxied in the Vue instance to ' +
'prevent conflicts with Vue internals. ' +
'See: https://vuejs.org/v2/api/#data',
target
)
}
 Copy code 

Used to detect attributes key Declaration method for , Whether it is $ perhaps _ At the beginning , If it is , A warning will be given , Take a simple example to see the effect :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="../vue.js"></script>
<div id="app">
<p>
{{$hhh}}
{{_dddd}}
</p>
</div>
<script>
const vm = new Vue({
el: '#app',
data() {
return {
$hhh: 'ddd',
_dddd: 'ffff'
}
},
})
console.log(vm)
</script>
</body>
</html>
 Copy code 

hasHandler

var hasHandler = {
/*target The object to be represented , key Properties accessed during external operations */
has: function has(target, key) {
/*key in target return true perhaps false*/
var has = key in target;
/* In the template engine , There are some attributes vm There is no agency , But it can also be used , image Number,Object etc. */
var isAllowed = allowedGlobals(key) ||
(typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data));
/* Above has and isAllowed by false Under the circumstances */
if (!has && !isAllowed) {
if (key in target.$data) {
warnReservedPrefix(target, key);
}
/*warnNonPresent function , When accessing properties , It doesn't exist vm For instance , There will be an error */
else {
warnNonPresent(target, key);
}
}
/*has perhaps isAllowed*/
return has || !isAllowed
}
};
 Copy code 

hasHandler Only configuration has hook , When doing propKey in proxy in The operator perhaps with() In operation , Will trigger has Hook function

hasHandler Looking for key when , Look in three directions

  • Acting target object adopt in The operator
  • Global object API allowedGlobals function
  • Find out if it's a built-in method for rendering functions The first character is marked with _ Start typeof key === 'string' && key.charAt(0) === '_'

hasHandler, First, check vm Whether the attribute exists on the instance , The following code is vm You can see that test

new Vue({
el:"#app",
template:"<div>{{test}}</div>",
data:{
test
}
})
 Copy code 

If in vm We didn't find , Then judge whether it is a global object , for example Number etc. , Number It's what language provides You can also use... In templates

new Vue({
el:"#app",
/*Number It belongs to the overall situation provided by language API*/
template:"<div> {{ Number(test) +1 }}</div>",
data:{
test
}
})
 Copy code 

getHandler

const getHandler = {
get(target, key) {
if (typeof key === 'string' && !(key in target)) {
// testing data Attribute key Is it right? $,_ start 
if (key in target.$data) warnReservedPrefix(target, key)
else warnNonPresent(target, key)
}
return target[key]
}
}
 Copy code 

initProxy

initProxy = function initProxy(vm) {
/*hasProxy Judge whether the current environment supports es Provided Proxy*/
if (hasProxy) {
// determine which proxy handler to use
var options = vm.$options;
/* Different conditions return different handlers, getHandler perhaps hasHandler */
var handlers = options.render && options.render._withStripped
? getHandler
: hasHandler;
/* agent vm example */
vm._renderProxy = new Proxy(vm, handlers);
} else {
vm._renderProxy = vm;
}
};
 Copy code 
版权声明
本文为[Official account Life code]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/05/20210503144051037N.html

  1. Why did gitlab choose vue.js?
  2. HTTP-RPC: 轻量跨平台REST服务
  3. 继全面采用Node.js以后,PayPal分享大幅度踩坑GraphQL心得 - Mark Stuart
  4. vue组件化开发实战之滚动/轮播的实现
  5. Http-rpc: lightweight cross platform rest Service
  6. Following the full adoption of node.js, PayPal shares a great deal of graphql experience mark Stuart
  7. Implementation of rolling / carousel in Vue component development
  8. CSS是什么?这一篇全解,绝对有你想要的
  9. What is CSS? This is a complete solution, there is absolutely what you want
  10. 04-HTML5常用标签-HTML5极速入门
  11. 04-html5 common tags
  12. WEB前端全套零基础视频教程+软件2021最新编程视频
  13. Web front end full set of zero basic video tutorial + software 2021 latest programming video
  14. 使用Node, Mongo, React, Redux实现Token认证
  15. Using node, Mongo, react and Redux to realize token authentication
  16. 体面编码之CSS和HTML
  17. CSS and HTML for decent coding
  18. 使用Playwright基于多浏览器进行javascript自动化测试的简单教程- Applitools
  19. A simple tutorial for JavaScript automatic testing based on multi browser using playwright - applitools
  20. Minimum distance to target element
  21. 浅谈 React 中的 XSS 攻击
  22. XSS attack in react
  23. 自学前端教程整理,附不容错过的前端100篇文章合集
  24. Self taught front-end tutorial collation, with a collection of 100 front-end articles that can not be missed
  25. 使用OpenTracing跟踪Go中的HTTP请求延迟
  26. Using opentracing to track HTTP request latency in go
  27. Encapsulating databinding allows you to write less than 10000 lines of code
  28. 03-HTML5标签-HTML5极速入门
  29. 03-html5 tag-html5 quick start
  30. LayUI - 极易上手拿来即用的前端 UI 框架
  31. Layui - easy to use front end UI framework
  32. Interpretation of lodash source code (1)
  33. Why is the first parameter of node family callback error?
  34. 报告:JavaScript 开发者达1380 万,C#超越 PHP,Rust 增长最快
  35. Report: Javascript developers reach 13.8 million, C surpasses PHP, and rust grows fastest
  36. 小白前端入门笔记(10),怎么设置网站内部的超链接?
  37. How to set up hyperlinks inside the website?
  38. Using node and socket to realize online chat room
  39. The core competitiveness of Vue: data bidirectional binding
  40. React configuration agent
  41. CSS layout
  42. Application scenario explanation of Vue dynamic component
  43. Redux learning notes 04 -- using multiple reducers to manage data
  44. After three months of typescript writing, what have I learned?
  45. Node family - what is a callback?
  46. React -- a simple implementation of render & create element
  47. JS learning simple usage of jquery
  48. Seamless love
  49. 小白前端入门笔记(12),设置哑链接
  50. Small white front-end entry notes (12), set dumb links
  51. Vue2. X opens composition API and TSX
  52. Interview record and thinking of social recruitment for one and a half years (Alibaba, Tencent, baidu offer)
  53. Flex learning notes
  54. The most essential closure article in the eastern hemisphere
  55. 2021-05-03 hot news
  56. Sword finger offer -- reverse order pair in array (JS Implementation)
  57. Working process of scaffold
  58. Use decorator mode to strengthen your fetch
  59. [JS] scope (Introduction)
  60. Employment information statistics network (interface document)