Principle and usage analysis of Vue js with statement

  • 2021-08-10 06:31:56
  • OfStack

The compilation part of vue source code has the following 1 code, which uses with:


export function generate (
 ast: ASTElement | void,
 options: CompilerOptions
): CodegenResult {
 const state = new CodegenState(options)
 const code = ast ? genElement(ast, state) : '_c("div")'
 return {
  render: `with(this){return $[code]}`,
  staticRenderFns: state.staticRenderFns
 }
}

The usage of with under 1 is explained in detail below:

One of the types we commonly use in js is objects:


let obj = {
  a:"aa",
  b:"bb",
  c:"cc"
}

When it comes to an object, we can get the property values in it by using the following methods:


// 1 : 
let a = obj.a
//2 : 
let b = ojb["b"]

To take out every attribute value in the object, we need obj...., which will virtually enter obj many times, so how can we simply get its attribute value?

1. Conventional methods:

var a = obj.a;
var b = obj.b;
var c = obj.c;

2. The method after using with:


with(obj){
  var a = a;
  var b = b;
  var c = c;
}

Here, the values in with parentheses are our public objects, and the following are the values in each object


var qs1 = location.search.substring(1);
var hostname1 = location.hostname;
var url1 = location.href;
 
//  The above lines of code all contain location Object, you can use the with Statement is shortened to the following form 
 
with(location){
  var qs2 = search.substring(1);
  var hostname2 = hostname;
  var url2 = href;
}

As long as it will undoubtedly greatly improve our efficiency.

But everything has advantages and disadvantages, and we have to mention the disadvantages of with:

The with statement is not recommended when developing large applications because of the performance degradation caused by heavy use of the with statement and the difficulty of debugging the code


Related articles: