2.Vue2全局Vue API

80 阅读1分钟

1. Vue.extend(options)——使用基础 Vue 构造器,创建一个“子类”Vue实例

  • 参数{Object} options

  • 用法

    使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象。

    data 选项是特例,需要注意 - 在 Vue.extend() 中它必须是函数

    <div id="mount-point"></div> 
    
    // 创建Vue构造器 
    var Profile = Vue.extend({   
        template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',   
        data: function () {     
            return {       
                firstName: 'Walter',       
                lastName: 'White',       
                alias: 'Heisenberg'     
            }   
        } 
     }) 
    // 创建 Profile 实例,并挂载到一个元素上。 
    new Profile().$mount('#mount-point') 
    

    结果如下:

    <p>Walter White aka Heisenberg</p> 
    

    image.png

    image.png

  • 参考组件

2. Vue.nextTick( [callback, context] )——在下次 DOM 更新循环结束之后进行延迟回调。

  • 参数

    • {Function} [callback]
    • {Object} [context]
  • 用法

    在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。

    // 修改数据 
    vm.msg = 'Hello' 
    // DOM 还没有更新
    Vue.nextTick(function () {   // DOM 更新了 })  
    // 作为一个 Promise 使用 
    Vue.nextTick().then(function () {     // DOM 更新了   }) 
    

    如果没有提供回调且在支持 Promise 的环境中,则返回一个 Promise。请注意 Vue 不自带 Promise 的 polyfill

    image.png

    image.png

  • 参考异步更新队列

3. Vue.set( target, propertyName/index, valu…—— 向响应式对象中添加新 property (响应式的)

  • 参数

    • {Object | Array} target
    • {string | number} propertyName/index
    • {any} value
  • 返回值:设置的值。

  • 用法

    向响应式对象中添加一个 property,并确保这个新 property 同样是响应式的,且触发视图更新。它必须用于向响应式对象上添加新 property,因为 Vue 无法探测普通的新增 property (比如 this.myObject.newProperty = 'hi')

    注意对象不能是 Vue 实例,或者 Vue 实例的根数据对象。

    image.png

4. Vue.delete( target, propertyName/index )——删除对象的 property触发更新视图

  • 参数

    • {Object | Array} target

    • {string | number} propertyName/index

  • 用法

    删除对象的 property。如果对象是响应式的,确保删除能触发更新视图。这个方法主要用于避开 Vue 不能检测到 property 被删除的限制,但是你应该很少会使用它。

    目标对象不能是一个 Vue 实例或 Vue 实例的根数据对象。

    image.png

  • 参考深入响应式原理

5. Vue.directive( id, [definition] )—— 注册或获取一个全局指令

  • 参数

    • {string} id
    • {Function | Object} [definition]
  • 用法

    注册或获取全局指令。

    // 注册 
    Vue.directive('my-directive', {  
        bind: function () {},   
        inserted: function () {},   
        update: function () {},   
        componentUpdated: function () {},   
        unbind: function () {} 
    })  
    // 注册 (指令函数) 
    Vue.directive('my-directive', function () {   
      // 这里将会被 `bind` 和 `update` 调用 
    })  
    // getter,返回已注册的指令 
    var myDirective = Vue.directive('my-directive') 
    

    image.png image.png

  • 参考自定义指令

6. Vue.filter( id, [definition] )——注册或获取一个全局过滤器

  • 参数

    • {string} id
    • {Function} [definition]
  • 用法

    注册或获取全局过滤器。

    // 注册 
    Vue.filter('my-filter', function (value) {   // 返回处理后的值 })  
    // getter,返回已注册的过滤器 
    var myFilter = Vue.filter('my-filter') 
    

    image.png

  • 参考过滤器

7. Vue.component( id, [definition] )——注册或获取一个全局组件

  • 参数

    • {string} id
    • {Function | Object} [definition]
  • 用法

    注册或获取全局组件。注册还会自动使用给定的 id 设置组件的名称

    // 注册组件,传入一个扩展过的构造器 
    Vue.component('my-component', Vue.extend({ /* ... */ }))  
    // 注册组件,传入一个选项对象 (自动调用 Vue.extend) 
    Vue.component('my-component', { /* ... */ })  
    // 获取注册的组件 (始终返回构造器) 
    var MyComponent = Vue.component('my-component') 
    

    image.png

  • 参考组件

8. Vue.use( plugin )——安装 Vue.js 相关插件

  • 参数

    • {Object | Function} plugin
  • 用法

    安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入。

    该方法需要在调用 new Vue() 之前被调用。

    当 install 方法被同一个插件多次调用,插件将只会被安装一次。

    image.png

  • 参考插件

9. Vue.mixin( mixin )——全局注册一个混入

  • 参数

    • {Object} mixin
  • 用法

    全局注册一个混入,影响注册之后所有创建的每个 Vue 实例。插件作者可以使用混入,向组件注入自定义的行为。不推荐在应用代码中使用

    image.png

  • 参考全局混入

10. Vue.compile( template )——将一个模板字符串编译成 render 函数

  • 参数

    • {string} template
  • 用法

    将一个模板字符串编译成 render 函数。只在完整版时可用

    var res = Vue.compile('<div><span>{{ msg }}</span></div>')  
    new Vue({
        el:"#app",
        data: {    
           msg: 'hello'   
        },   
        render: res.render,   
        staticRenderFns: res.staticRenderFns 
    }) 
    

    image.png

  • 参考渲染函数

    image.png

    image.png

    image.png

11. Vue.observable( object )—— 让一个对象可响应

  • 参数

    • {Object} object
  • 用法

    让一个对象可响应。Vue 内部会用它来处理 data 函数返回的对象。

    返回的对象可以直接用于渲染函数计算属性内,并且会在发生变更时触发相应的更新。也可以作为最小化的跨组件状态存储器,用于简单的场景:

    const state = Vue.observable({ count: 0 })  
    const Demo = {   
        render(h) {     
          return h('button', {
            on: { click: () => { state.count++ }}
          }, `count is: ${state.count}`)
    } 
    

    在 Vue 2.x 中,被传入的对象会直接被 Vue.observable 变更,所以如这里展示的,它和被返回的对象是同一个对象。在 Vue 3.x 中,则会返回一个可响应的代理,而对源对象直接进行变更仍然是不可响应的。因此,为了向前兼容,我们推荐始终操作使用 Vue.observable 返回的对象,而不是传入源对象。

    image.png

    image.png

    /**
     * Observer class that is attached to each observed
     * object. Once attached, the observer converts the target
     * object's property keys into getter/setters that
     * collect dependencies and dispatch updates.
     */
    export class Observer {
      value: any;
      dep: Dep;
      vmCount: number; // number of vms that have this object as root $data
    
      constructor (value: any) {
        this.value = value
        this.dep = new Dep()
        this.vmCount = 0
        def(value, '__ob__', this)
        if (Array.isArray(value)) {
          if (hasProto) {
            protoAugment(value, arrayMethods)
          } else {
            copyAugment(value, arrayMethods, arrayKeys)
          }
          this.observeArray(value)
        } else {
          this.walk(value)
        }
      }
    
      /**
       * Walk through all properties and convert them into
       * getter/setters. This method should only be called when
       * value type is Object.
       */
      walk (obj: Object) {
        const keys = Object.keys(obj)
        for (let i = 0; i < keys.length; i++) {
          defineReactive(obj, keys[i])
        }
      }
    
      /**
       * Observe a list of Array items.
       */
      observeArray (items: Array<any>) {
        for (let i = 0, l = items.length; i < l; i++) {
          observe(items[i])
        }
      }
    }
    
  • 参考深入响应式原理

12. Vue.version——提供字符串形式的 Vue 安装版本号

  • 细节:提供字符串形式的 Vue 安装版本号。这对社区的插件和组件来说非常有用,你可以根据不同的版本号采取不同的策略。

  • 用法

    image.png

    var version = Number(Vue.version.split('.')[0])
    if (version === 2) {
    // Vue v2.x.x
    } else if (version === 1) {
    // Vue v1.x.x
    } else {
    // Unsupported versions of Vue
    }
    

    image.png image.png

image.png