>  기사  >  웹 프론트엔드  >  Vue 글로벌 API에 대한 심층적인 이해

Vue 글로벌 API에 대한 심층적인 이해

小云云
小云云원래의
2017-12-18 13:50:342321검색

API는 다들 아시죠? 이 글은 주로 Vue 공식 문서의 글로벌 API에 대한 심층적인 이해를 소개하고 있습니다. 편집자는 꽤 좋다고 생각하므로 지금 공유하고 참고용으로 제공하겠습니다. 편집자를 따라 살펴보겠습니다. 모두에게 도움이 되기를 바랍니다.

Vue.extend

구성 항목 데이터가 작동해야 합니다. 그렇지 않으면 구성이 유효하지 않습니다. 데이터 병합 규칙("Vue 공식 문서 - 전역 구성" 참조) 소스 코드는 다음과 같습니다.

비함수 유형 데이터를 전달합니다(위 그림의 데이터 구성은 {a:1). }), 옵션 병합 후 이때 데이터가 함수형이 아닌 경우 개발 버전에서는 경고를 발행한 후 바로 parentVal을 반환하는데, 이는 확장으로 전달된 데이터 옵션이 무시된다는 의미입니다.

Vue를 인스턴스화할 때 데이터가 객체가 될 수 있다는 것을 알고 있습니다. 여기서 병합 규칙은 보편적이지 않나요? 위에는 if(!vm) 판단이 있습니다. vm은 인스턴스화될 때 값을 가지므로 Vue.extend와는 다릅니다. 실제로 다음 주석도 이에 대해 설명합니다(Vue.extend 병합에서는 둘 다 함수여야 합니다). ) 이것이 공식 문서에 데이터가 특별한 경우라고 나와 있는 이유입니다.

또한 공식 문서에 언급된 "하위 클래스"는 Vue.extend가 Vue를 "상속"하는 함수를 반환하기 때문입니다. 소스 코드 구조는 다음과 같습니다.


Vue.extend = function (extendOptions) {
  //***
  var Super = this;
  var SuperId = Super.cid;
  //***
  var Sub = function VueComponent(options) {
    this._init(options);
  };
  Sub.prototype = Object.create(Super.prototype);
  Sub.prototype.constructor = Sub;
  //***
  return Sub
};

Vue.nextTick

Vue를 사용하기 때문에 당연히 데이터 기반 방식으로 생각해야 합니다. 소위 데이터 기반이라는 것은 DOM에 대한 모든 작업을 Vue의 다양한 명령을 사용하여 완료할 수 있다는 의미입니다. 명령을 통해 데이터를 DOM에 "바인딩"하면 DOM 업데이트가 가능해질 뿐만 아니라 더욱 편리해집니다.

브라우저가 Promise를 지원하거나 Promise 라이브러리를 사용하는 경우(그러나 소스 코드의 판단은 Promise 유형 !== '정의되지 않음'이므로 외부에 노출된 것은 Promise라고 불러야 함) nextTick은 Promise 객체를 반환합니다. .


Vue.nextTick().then(() => {
  // do sth
})

Vue에서 nextTick을 실행하는 콜백은 cb.call(ctx) 호출 메서드를 사용합니다. ctx는 현재 Vue 인스턴스이므로 이를 사용하여 콜백에서 인스턴스 구성을 직접 호출할 수 있습니다.
nextTick은 단순히 실행을 위해 콜백을 마지막에 두는 것으로 이해하면 됩니다. 현재 소스 코드에서 Promise와 MutationObserver가 지원되지 않는 경우 콜백을 실행하기 위해 setTimeout 메서드를 사용하게 됩니다. 실행.


 if (typeof Promise !== 'undefined' && isNative(Promise)) {
 } else if (typeof MutationObserver !== 'undefined' && (
     isNative(MutationObserver) ||
     // PhantomJS and iOS 7.x
     MutationObserver.toString() === '[object MutationObserverConstructor]'
   )) {
 } else {
   // fallback to setTimeout
   /* istanbul ignore next */
   timerFunc = function () {
     setTimeout(nextTickHandler, 0);
   };
 }

실제로 살펴보기 위해 예를 들어보겠습니다.


<p id="app">
  <p ref="dom">{{a}}</p>
</p>
new Vue({
  el: &#39;#app&#39;,
  data: {
    a: 1
  },
  mounted: function name(params) {
    console.log(&#39;start&#39;);
    this.$nextTick(function () {
      console.log(&#39;beforeChange&#39;, this.$refs.dom.textContent)
    })
    this.a = 2;
    console.log(&#39;change&#39;);
    this.$nextTick(function () {
      console.log(&#39;afterChange&#39;, this.$refs.dom.textContent)
    })
    console.log(&#39;end&#39;);
  }
})
// 控制台依次打印
// start
// change
// end
// beforeChange 1
// afterChange 2

조금 혼란스러울 수 있습니다. 왜 beforeChange가 2가 아닌 1을 출력합니까? this .a=2 뒤에서 트리거된 dom 업데이트도 nextTick을 사용합니다. 위 코드의 실제 실행 순서는 beforeChange>update dom>afterChange입니다.

Vue.set

Vue.set( target, key, value ), target은 Vue 인스턴스 또는 Vue 인스턴스의 루트 데이터 객체일 수 없습니다. 소스 코드에서 다음 판단이 이루어지기 때문입니다.


var ob = (target).__ob__;
if (target._isVue || (ob && ob.vmCount)) {
"development" !== &#39;production&#39; && warn(
  &#39;Avoid adding reactive properties to a Vue instance or its root $data &#39; +
  &#39;at runtime - declare it upfront in the data option.&#39;
);
return val
}

target ._isVue는 Vue 인스턴스에 속성을 추가하는 것을 방지하고, ob && ob.vmCount는 Vue 인스턴스의 루트 데이터 객체에 속성을 추가하는 것을 방지합니다.

Vue.delete

Vue가 삭제 작업을 감지할 수 있으면 이 API는 나타나지 않습니다. $data 속성을 삭제하기 위해 삭제를 사용해야 하는 경우 Vue.delete를 사용하세요. 그렇지 않으면 dom 업데이트가 트리거되지 않습니다.

Vue.set과 마찬가지로 Vue.delete(대상, 키)의 대상은 Vue 인스턴스 또는 Vue 인스턴스의 루트 데이터 객체가 될 수 없습니다. 소스코드의 차단 방식은 Vue.set과 동일합니다.

버전 2.2.0+에서는 대상이 배열인 경우 키는 배열 첨자입니다. Vue.delete는 실제로 배열을 삭제하기 위해 splice를 사용하기 때문에 delete를 사용하여 배열을 삭제할 수는 있지만 위치는 그대로 유지되며 실제 삭제로 간주될 수 없습니다.


var a = [1, 2, 3];
delete a[0];
console.log(a); // [undefined, 2, 3]

Vue.use

Vue.use 소스 코드는 비교적 간단하며 전체 내용을 게시할 수 있습니다.


Vue.use = function (plugin) {
  var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));
  if (installedPlugins.indexOf(plugin) > -1) {
    return this
  }
  // additional parameters
  var args = toArray(arguments, 1);
  args.unshift(this);
  if (typeof plugin.install === &#39;function&#39;) {
    plugin.install.apply(plugin, args);
  } else if (typeof plugin === &#39;function&#39;) {
    plugin.apply(null, args);
  }
  installedPlugins.push(plugin);
  return this
};

설치된 플러그인은 installPlugins에 배치됩니다. 플러그인을 설치하기 전에 installPlugins.indexOf(plugin)를 사용하여 해당 플러그인이 이전에 설치되었는지 확인하여 동일한 플러그인을 방지합니다. 여러 번 등록되는 것을 방지합니다.

플러그인 유형은 객체이며, 플러그인을 설치하려면 설치 속성을 지정해야 합니다(typeofplugin.install === 'function'). 또한 플러그인 실행은plugin.install.apply를 사용합니다. (plugin, args); 따라서 객체 속성의 다른 부분에 액세스합니다. 여기서 args는 Vue(args.unshift(this);) 및 Vue.use(toArray(arguments, 1), 1은 인수[1]에서 시작하여 가로채기를 의미함)에 의해 전달된 플러그인 이외의 매개변수입니다.


Vue.use({
  a: 1,
  install: function (Vue) {
    console.log(this.a) // 1
    console.log(arguments) // [function Vue(options),"a", "b", "c"]
  }
}, &#39;a&#39;, &#39;b&#39;, &#39;c&#39;)

플러그인 유형은 function이고 설치 시 플러그인.apply(null, args);를 호출하므로 엄격 모드에서는 플러그인 런타임 컨텍스트가 null이고 비엄격 모드에서는 null입니다. 창입니다.


&#39;use strict&#39;
Vue.use(function plugin() {
  console.log(this) // null
  console.log(arguments) // [function Vue(options),"a", "b", "c"]
}, &#39;a&#39;, &#39;b&#39;, &#39;c&#39;)

Vue.compile

和众多 JS 模板引擎的原理一样,预先会把模板转化成一个 render 函数,Vue.compile 就是来完成这个工作的,目标是将模板(template 或 el)转化成 render 函数。
Vue.compile 返回了{render:Function,staticRenderFns:Array},render 可直接应用于 Vue 的配置项 render,而 staticRenderFns 是怎么来的,而且按照官网的例子,Vue 还有个隐藏的配置项 staticRenderFns,先来个例子看看。


var compiled = Vue.compile(
  &#39;<p>&#39; +
  &#39;<header><h1>no data binding</h1></header>&#39; +
  &#39;<section>{{prop}}</section>&#39; +
  &#39;</p>&#39;
)
console.log(compiled.render.toString())
console.log(compiled.staticRenderFns.toString())
// render
function anonymous() {
  with(this) {
    return _c(&#39;p&#39;, [_m(0), _c(&#39;section&#39;, [_v(_s(prop))])])
  }
}
// staticRenderFns
function anonymous() {
  with(this) {
    return _c(&#39;header&#39;, [_c(&#39;h1&#39;, [_v("no data binding")])])
  }
}

原来没有和数据绑定的 dom 会放到 staticRenderFns 中,然后在 render 中以_m(0)来调用。但是并不尽然,比如上述模板去掉4a249f0d628e2318394fd9b75b4636b1,staticRenderFns 长度为 0,header 直接放到了 render 函数中。


function anonymous() {
  with(this) {
    return _c(&#39;p&#39;, [_c(&#39;header&#39;, [_v("no data binding")]), _c(&#39;section&#39;, [_v(_s(prop))])])
  }
}

Vue.compile 对应的源码比较复杂,上述渲染 1aa9e5d373740b65a0cc8f0a02150c53 没有放到 staticRenderFns 对应源码的核心判断如下:


 // For a node to qualify as a static root, it should have children that
 // are not just static text. Otherwise the cost of hoisting out will
 // outweigh the benefits and it&#39;s better off to just always render it fresh.
 if (node.static && node.children.length && !(
     node.children.length === 1 &&
     node.children[0].type === 3
   )) {
   node.staticRoot = true;
   return
 } else {
   node.staticRoot = false;
 }

1aa9e5d373740b65a0cc8f0a02150c53 不符判断条件 !(node.children.length === 1 && node.children[0].type === 3), 1aa9e5d373740b65a0cc8f0a02150c53 有一个子节点 TextNode(nodeType=3)。 注释也说明了一个 node 符合静态根节点的条件。

另外官网说明了此方法只在独立构建时有效,什么是独立构建?这个官网做了详细的介绍,不再赘述。对应官网地址:对不同构建版本的解释。

仔细观察编译后的 render 方法,和我们自己写的 render 方法有很大区别。但是仍然可以直接配置到 render 配置选项上。那么里面的那些 _c()、_m() 、_v()、_s() 能调用?随便看一个 Vue 的实例的 __proto__ 就会发现:


// internal render helpers.
// these are exposed on the instance prototype to reduce generated render
// code size.
Vue.prototype._o = markOnce;
Vue.prototype._n = toNumber;
Vue.prototype._s = toString;
Vue.prototype._l = renderList;
Vue.prototype._t = renderSlot;
Vue.prototype._q = looseEqual;
Vue.prototype._i = looseIndexOf;
Vue.prototype._m = renderStatic;
Vue.prototype._f = resolveFilter;
Vue.prototype._k = checkKeyCodes;
Vue.prototype._b = bindObjectProps;
Vue.prototype._v = createTextVNode;
Vue.prototype._e = createEmptyVNode;
Vue.prototype._u = resolveScopedSlots;
Vue.prototype._g = bindObjectListeners;

正如注释所说,这些方法是为了减少生成的 render 函数的体积。

全局 API 还剩 directive、filter、component、mixin,这几个比较类似,而且都对应着配置项,会在「选项」中再详细介绍。

相关推荐:

Vue官方文档梳理的全局配置详解

Vue拦截器vue-resource 拦截器使用详解

vue项目的构建,打包,发布详解

위 내용은 Vue 글로벌 API에 대한 심층적인 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.